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?
The only time I would say you definitely shouldn't return early is if you can't easily see every return within a single screen (whatever the standard might be for people working on the same code base), you should at the very least be adding comments indicating that the function can return early if there is an early return.
The only time I would say you definitely should return early is if your code looks like...
If you find yourself in either of these situations, however... you should probably be refactoring the function.
If exceptions aren't part of the picture, I prefer returning immediately when I can.
It can be easy to mismanage the flag variable and I'm against flag variables in general. Not returning also might make a maintainer think that further work might be done (if the method is long).
Honestly I think it depends on the situation. Personally I use both, and I decide based on which one will make the code more clear and easy to read.
If you have heavily nested if statements (or any other control structure) and it may get confusing, then I would return inside the statements
Don't worry too much about what is 'best practice' in this case, as it is more important that the code is clear and easy to understand. Use what feels right for the situation.
Personally, I like the second method better. It is straightforward and clearer to me, but I do know there are people who must have only one return in a function.
For this case, I prefer:
In general, I like to use early return to handle error conditions, and return at the end to return computed results.
I prefer returning early and avoiding deep nesting. This is particularly true right at the start of the method: test anything that's simple, and get out (or throw an exception) if you can do so really early.
If it's right in the middle of a method, it's more of a judgement call.
Note that I'd refactor your example straight away to use a single
if
:I realise this was only a toy example, but my point is that it's always worth looking for more ways to simplify your code :)