PHPnews.io

★ Avoid using else

Written by murze.be / Original link on Mar. 16, 2022

Using else often encourages complexer code structure, makes code less readable. In most cases you can refactor it using early returns.

In this piece of code, it takes some brainpower to determine when those else conditions will be reached.

if ($conditionA) {
if ($conditionB) {
// condition A and B passed
   }
else {
// condition A passed, B failed
   }
}
else {
// condition A failed
}

Using early returns this becomes much more readable, because there aren't as many nested paths to follow. Our code has become more linear.

if (! $conditionA) {
// condition A failed

return;
}

if (! $conditionB) {
// condition A passed, B failed

return;
}

// condition A and B passed

Flattening code" by removing nested structures makes it so that we don't have to think as hard to understand the possible paths our code can take. It has a significant impact on readability.

To get more tips on code readability subscribe to the mailinglist at Writing Readable PHP.

murze

« Clean Coders Hate What Happens to Your Code When You Use These Enterprise Programming Tricks - How to improve privacy with Laravel file encryption »