Hey I have been programming for a few years now and just recently I was wondering what is best to do in a method that is always going to return something:
if($age < 18) {
return 'Under 18';
}
else {
return 'Adult';
}
Or is it better to use:
if($age < 18) {
return 'Under 18';
}
return 'Adult';
In the latter if they are under 18 the program will return ‘Under 18’ and terminate the rest of the function so is there any need for that else{} in the first example? Thanks.
It’s better to return early. Nested if elses make conditionals even worse!
Simplified (no elses) Example
Explanation
The reason returning early is desired is because (in my opinion) of how the brain processes nested ifs. You will notice yourself when reading a nested if structure you always seem to keep track of the previous if conditions. If you flatten it out like i did it’s easier for your brain to process (weird considering it does the same thing).
Returning early in general is better because you don’t have to read ALL the code up until the return statement – it’s also faster to execute but how much faster depends on the code itself.
Further Reading
https://softwareengineering.stackexchange.com/questions/118703/where-did-the-notion-of-one-return-only-come-from