[Solved] Best practice to use else{} or use return? [closed]


It’s better to return early. Nested if elses make conditionals even worse!

Simplified (no elses) Example

//nested (without return)
if ($a == 1) {
    if ($a == 2) {
        if ($a > 2) {

        }
    }
}

//return early
if ($a == 1) {
    return 1;
}

if ($a == 2) {
    return 2;
}

if ($a > 3) {
    return $a;
}

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

12

solved Best practice to use else{} or use return? [closed]