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?
To have readable and maintainable code within a function, use multiple early returns instead of having nested if statements. Doing so will reduce the cyclomatic complexity of the code and easily add new changes.
Multiple return statements in a method will cause your code not to be purely object-oriented. Here you'll find an example where you can use a clean OOP approach instead of using multiple returns.
R eturn early is the way of writing functions or methods so that the expected positive result is returned at the end of the function and the rest of the code terminates the execution (by returning or throwing an exception) when conditions are not met.
You can return only one value in Java. If needed you can return multiple values using array or an object.
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.
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
:
boolean validate(DomainObject o) {
if (o.property == x || o.property2 == y) {
return true;
} ...
return false;
}
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 :)
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