DEV Community

Discussion on: A simple tip for cleaner code

Collapse
 
dallgoot profile image
dallgoot • Edited

personally i'd go with the less conventionnal :

        function foo($bar) 
        {
            if ($bar > 0) return "YES";
            if ($bar == 0) return "MAYBE";
            return "NO";    
        }  

..somewhere between ternary and switch disposition, i find it clearer, obvious and fautless performance-wise.
The point of concern is when another dev replace the return with more operations defeating the "escape" purpose of "return" statement.
So i can understand that the "else" are somewhat preventing falling through.
However, as $bar cannot at the same time be 0 AND superior to 0 AND something else, i'd say it's safe.

In terms of control structure it calls for a switch, however many people reject this form :

function foo($bar)
{
    switch(true) {
        case ($bar > 0):  return "YES";
        case ($bar == 0): return "MAYBE";
        default:
            return "NO";
    }
}