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?
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);
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With