Avoid using else original

by Freek Van der Herten – 1 minute read

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.

Join 9,500+ smart developers

Get my monthly newsletter with what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

"Freek publishes a super resourceful and practical newsletter. A must for anyone in the Laravel space"

Joey Kudish — Shipping with AI as a teammate

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share? Submit a link to the community section.