Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad style to not use the loop variable in for-each statements in Java? [closed]

Is it considered poor style / discourage to ignore the loop variable in a for-each statement in Java?

I have some code looks looks sort of like the following:

public void makeChecklist( final List<File> inputSrcs ){

   for( File src : inputSrcs ){
      System.out.print( src.getName() + "\t" );
   }
   System.out.println();


   for( File src : inputSrcs ){
      //Not using "src" in this body!
      System.out.print( "[ ]\t" );
   }
   System.out.println();

}

Is this a bad idea? Any reason not todo things this way? It just seems so much cleaner than using a regular for-loop.


PS- presume that for the example above I want the checkboxes to appear underneath the names, the example is contrived to ilustrate my question as simply as possible.

like image 266
Sled Avatar asked Dec 28 '22 07:12

Sled


1 Answers

It certainly looks odd. I would make it clearer that it's only the count that matters with a for loop:

for (int i = 0; i < inputSrcs.size(); i++) {
    System.out.println( "[ ]\t" );
}

I think that makes the intention clearer. Although as has been pointed out in the comments, we're really just replacing one "dummy" variable with another in the above. What I like about it is that it explicitly calls size(), which I believe shows that the size is important.

In a more expressive language you might find something to indicate "I just want to execute the body n times" which would be prettier still:

inputSrcs.size().times() {
    System.out.println( "[ ]\t" );
}

(That may or may not be valid Groovy :)

EDIT: Another obvious answer occurs to me, which should have occurred before:

printRepeatedly("[ ]\t", inputSrcs.size());

...

private static void printRepeatedly(String text, int count) {
    for (int i = 0; i < count; i++) {
        System.out.println(text);
    }
}

Now in the calling method, the meaning is absolutely obvious... and within printRepeatedly we don't even have the context of a list, so we couldn't possibly be trying to use the data. At this point the dummy variable i is fairly obviously a dummy variable, and the method name makes it obvious why we'd want this behaviour.

like image 73
Jon Skeet Avatar answered Dec 31 '22 13:12

Jon Skeet