This is probably a bit subjective, but I’m in fact looking for answers that contain some reasoning.
I’ve met the following two programming styles for conditions in loop bodies. This:
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].isEmpty())
continue;
doSomeStuff();
doSomeMoreStuff();
}
And this:
for (int i = 0; i < myArray.length; i++) {
if (!myArray[i].isEmpty()) {
doSomeStuff();
doSomeMoreStuff();
}
}
I’ve usually used the first style, because it keeps indentation levels sane, especially when there’s more than one condition. But I began to wonder if the second isn’t actually cleaner. Do you have a preferred style and can you explain why?
Update:
Here’s a more realistic example. Imagine I’m reading a file like this “First name: Last name”, e.g.:
John;Doe
Joe;Bloggs
This is how I read each line into a name object, ignoring empty lines (which may occur):
while (line = file.readLine()) {
if (line.isEmpty())
continue;
String[] columns = line.split(";");
names.add(new Name(columns[0], columns[1]));
}
The fact is that the second increases cyclomatic complexity and may lead to the arrowhead antipattern.
In addition, keeping all your “code should not pass this point” checks at the beginning allows you to group them together, which means they are easier to maintain imho.