开发者

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

开发者 https://www.devze.com 2023-01-16 18:03 出处:网络
Closed. This question is opinion-based. It is not currently accepting answer开发者_开发百科s. Want to improve this question? Update the question so it can be answered with facts and citati
Closed. This question is opinion-based. It is not currently accepting answer开发者_开发百科s.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 7 years ago.

Improve this question

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.


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.


I think if you're going to do it, the comment removes a lot of the ambiguity/potential confusion.


Seems perfectly clear to me.

You will find that the line feeds added by println()--as opposed to print()--will make it so your check boxes aren't really lining up with anything other than your left margin.

0

精彩评论

暂无评论...
验证码 换一张
取 消