Duplicate: Should a function have only one return statement?
Often times you might have a method that checks numerous conditions and returns a status (lets say boolean for now). Is it better to define a flag, set it during the method, and return it at the end :
boolean validate(DomainObject o) {
boolean valid = false;
if (o.property == x) {
valid = true;
} else if (o.property2 == y) {
valid = true;
} ...
return valid;
}
or is it better/more correct to simply return once you know the method's outcome?
boolean validate(DomainObject o) {
if (o.property == x) {
return true;
} else if (o.property2 == y) {
return true;
} ...
return false;
}
Now obviously there could be try/catch blocks and all other kinds of conditions, but I think the concept is clear. Opinions?
As with most coding styles, it's really a matter of preference, but guard clauses are considered by many to be a best practice.
If it's a method you'll be calling thousands of times, then early return is better to achieve a [slightly] increased performance.
If not, then I'd prefer late return, since it improves readability.
Remember programmers usually spend more time reading than writing code, so anything you can do to improve readability will be certainly welcome.
To me, this is sort of one of those religious war topics with no correct answer. The argument against returning early essentially boils down to the fact that having one and only one point where a function can exit reduces the number of possible paths through your code, thus, in theory at least, reducing the chances for bugs. My personal style is to, in situations where it makes sense to return early do so, and in situations where it makes sense to limit to one return statement I do that.
There are two factors pulling against each other.
The first factor is ease of debugging. If you return immediately (as shown in your second code snippet), it sometimes becomes difficult to debug a big function since it is hard to find these return statements, specially if they were put there by mistake.
The second factor is ease of implementation. If you are checking basic correctness of arguments at the beginning of the function and there is a long piece of code before the function finishes, you might have to put that entire code in a condition loop. If you don't, at some point the argument might get used for some long calculation, wasting time, because it would ultimately be rejected anyways.
So, the answer could be like this: