While working on a codebase that has a lot of legacy code I noticed a lot of functions written like this. For some reason, the older devs in the team preferred to write them this way, and much to my annoyance they still do.
// Not so nice.
function foo($bar)
{
if ($bar > 0) {
return "YES";
} else if ($bar == 0) {
return "MAYBE"
} else {
return "NO";
}
}
// Not so nice as well.
function foo($bar)
{
$value = '';
if ($bar > 0) {
$value = "YES";
} else if ($bar == 0) {
$value = "MAYBE"
} else {
$value = "NO";
}
return $value;
}
In my opinion, that's too much noise for your brain, we can make it a lot more readable just by utilising early returns.
// Very much nice, yes, yes, sexy.
function foo($bar)
{
if ($bar > 0) {
return "YES";
}
if ($bar == 0) {
return "MAYBE";
}
return "NO";
}
Isn't it a lot cleaner now? Don't be a dinosaur, use early returns!
Both listings have early returns, it's just that the elses in the first listing aren't really needed