Is it a bad style not to use a for-each loop variable in Java?

Is this unsatisfactory style / prevent ignoring loop variable in for-each expression in Java?

I have the look of the code something like this:

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(); } 

It is a bad idea? Any reason not to do it this way? This seems a lot cleaner than using a regular loop.


PS- suppose that for the above example I want the checkboxes to appear under the names, this example has managed to tell about my question as simply as possible.

+4
source share
3 answers

I think that if you do this, the comment will remove a lot of uncertainty / potential confusion.

+2
source

It certainly looks weird. I would clarify that this is only an account that matters with a for loop:

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

I think this makes the intention clearer. Although, as noted in the comments, we really just replace one dummy variable with another in the above. I like that he explicitly calls size() , which, in my opinion, shows that size is important.

In a more expressive language, you can find something indicating "I just want to execute the body n times", which would be even more beautiful:

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

(This may or may not be valid Groovy :)

EDIT: I get another obvious answer that should have happened earlier:

 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 value is absolutely obvious ... and inside printRepeatedly we donโ€™t even have a list context, so we could not try to use the data. For the time being, the dummy variable i is obviously a dummy variable, and the method name makes it obvious why we want this behavior.

+8
source

Seems perfectly clear to me.

You will find that the lines added by println () - unlike print (), make your flags not line up with anything other than your left margin.

0
source

All Articles