Menu

#1215 AvoidInstantiatingObjectsInLoops matches the right side of a list iteration loop

PMD-5.1.2
closed
PMD
4-Minor
Bug
5.1.1
2014-07-20
2014-07-01
No

Ok, so this is something you'd almost/arguably never see in good code, but... I did have a case where it came up for more or less valid reasons, and aside from whether it could be avoided with some best practices about variables and code structure it's not part of the repetition of a loop and therefore shouldn't be flagged by the rule java-optimizations/AvoidInstantiatingObjectsInLoops:

import java.util.ArrayList;
import java.io.File;

public class TestInstantiationInLoop {
    public static void main(String args[]) {
        for (String test : new ArrayList<String>()) { // facetious but simple example
            System.out.println(test);
        }
        for (String filename : new File("subdirectory").list()) { // complex but realistically conceivable (albeit exagerrated/oversimplified/rarely advisable) example
            System.out.println(filename);
        }
    }
}

The following should produce nothing, but reports both of the above loops:

pmd -d TestInstantiationInLoop.java -R java-optimizations/AvoidInstantiatingObjectsInLoops

Discussion

  • Andreas Dangel

    Andreas Dangel - 2014-07-12
    • status: open --> closed
    • assigned_to: Andreas Dangel
    • Milestone: New Tickets --> PMD-Next
     
  • Andreas Dangel

    Andreas Dangel - 2014-07-12

    This will be fixed with the next release.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.