Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you place if immediately after for in Java?

Tags:

java

Eclipse lets me write some code like this, and doesn't show any errors:

for (SomeClass c : listOfSomeClass) if (c.someBoolean) {
    // actions to take if someBoolean is true
}

Will this behave as expected, or is this not valid Java?

like image 835
John Avatar asked Nov 30 '22 20:11

John


2 Answers

It's valid. The if will get repeated as many times as there are elements of listOfSomeClass. But that doesn't mean that writing Java like this is a good idea. Please don't ever do this.

You could even write something like

for (SomeClass c : listOfSomeClass) if (c.someBoolean) System.out.println(c);

if you were feeling particularly perverse.

However, when you write code, it's important to write code that another programmer can easily read, understand, and modify if necessary. Once a software system is in production, you can be fairly sure that changes will be required in it at some point in the future. What you can't be sure of is exactly what those changes will be.

So a good programmer, a professional programmer, writes his/her code in a way that makes it as easy as possible to change; and that means as easy as possible to understand. Now we professional programmers get used to seeing code laid out in certain ways. Curly braces used with for and with if, whether they're actually required or not. Consistent indentation. Intuitive use of variable names, and so on. Anything slightly unusual slows us down.

I don't want to be scratching my head, trying to work out how code works. I don't want to have to THINK about which lines are part of the for loop, or the if branch. I want code that tells me what it does, the first time I cast my eyes upon it. So, if you are EVER on the same team as me - or on the same team as any programmer who vaguely resembles me - then for the love of all that is good in this world, write this loop exactly like this.

for (SomeClass element : listOfSomeClass) {
    if (element.shouldBePrinted()) {
        System.out.println(element);
    }
}
like image 157
Dawood ibn Kareem Avatar answered Dec 08 '22 01:12

Dawood ibn Kareem


It works fine, but the formatting it likely to be confusing. Even you are not sure of what it will do. I suggest you use the standard formatter in eclipse to produce something like

for (SomeClass c : listOfSomeClass) 
    if (c.someBoolean) {
        // actions to take if someBoolean is true
    }
like image 35
Peter Lawrey Avatar answered Dec 07 '22 23:12

Peter Lawrey