Possible Duplicate:
Should a function have only one return statement?
This is what I am talking about.
if (condition) {
aVariable = 1;
return;
}
doSomething();
if (condition) {
aVariable = 1;
} else {
doSomething();
}
Is one of these preferred over the other (conventions, etc)?
Every return statement is inside an if statement. While it may be logically impossible as written, the compiler needs a return for when none of the if evaluate true.
It depends on the semantics of your code, if the else branch is the point of the method, i.e. it's named after what happens in the else branch, the early return is probably correct, especially if the first part is some sort of check.
The return here is probably used in order to "improve" the performance of the method, so that other comparisons are not executed, once the needed scenario is performed.
Is it possible to write return statement in if block? It is possible, but you haven't covered all the possible cases to which the program flow may go.
Returning early can improve readability by reducing nesting in your code.
In some languages it is best practice to have a single return statement, for example in C++ you should allocate at the top and de-allocate at the bottom of your method, but Java is not such a language so prefer readability over a single return statement.
Many people use the single return rule because they don't understand why it exists or because they have a background in managed languages.
Please Note
Before you comment about the "one true way" of writing code, please pause for a moment and consider the following.
Why must there be only a single return statement?
If you can't think of a good reason, stop arguing that it should be the case.
Readability is most important. So early returns on begining of functions are ok, but once method starts doing something more complicated than checking its imputs/state of object, it should have only one return .
And if it is too complicated, it should be refactored to multiple functions.
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