As you know, in Eclipse you can turn on “Unnecessary ‘else’ statement” check that will trigger on if-then-else with premature return. And, from my experience, there are two most possible situations when use such statement:
1) Pre-check:
if (!validate(arg1)) {
return false;
}
doLotOfStuff();
2) Post-check:
doLotOfStuff();
if (condition) {
return foo;
} else {
return bar;
}
In the second case, if the trigger is on, Eclipse will suggest you to change the code to:
doLotOfStuff();
if (condition) {
return foo;
}
return bar;
However, I think that the return with else statement is more readable as it is like direct mapping of business logic. So I am curios if this “Unnecessary ‘else’ statement” code convention is widespread or code with else statement is more preferable?
Generally I would prefer the structure of the code to follow the structure of the underlying “business” logic. In this case, my approach would depend what
conditionrepresents. If it is an error check, for example, which won’t normally be hit but might occasionally be used, then the asymmetry of the second form matches the asymmetry of the logic.But if either possibility is reasonable and it’s simply a choice between them, I would allow the structure of the code to show that symmetry.
The code is there for the programmer to read, not the compiler.