php

Writing readable PHP: decrease indentation by returning early

freekmurze

Freek Van der Herten

Posted on March 11, 2020

Writing readable PHP: decrease indentation by returning early

When working older code, or code submitted through PRs, I sometimes see this pattern:

public function doSomething($someParameter)
{
    /** can be any kind of test */
    if ($someParameter === 0) {
        // do the actual work
    }
}

At the beginning of the function, there's a test being performed. The actual work is in the if block.

This can be refactored by reversing the condition and using an early return.

public function doSomething($someParameter)
{
    if ($someParameter !== 0) {
        return;
    }

    // do the actual work
}

Doing this has a couple of benefits:

  1. A level of indention is lost. This alone makes it more pleasant to read. You don't need to keep in your head that the code is wrapped in something.
  2. Using an early return is great for humans too. When somebody reading your code is interested in the case concerning the early return, he or she doesn't need further that that early return. In the first example, there could still be some code to be executed after the if block.
  3. When you're respecting a line length limit (you should), you now have more characters available when performing the actual work.

This technique also works when there are multiple conditions. Consider this function:

public function doSomething($someParameter, $someOtherParameter)
{
    /** can be any kind of test */
    if ($someParameter === 0) {
        if ($someOtherParameter === 0) {
            // do the actual work
        }
    }
}

By using early returns, you can rewrite it to something more readable.

public function doSomething($someParameter, $someOtherParameter)
{
    if ($someParameter !== 0) {
        return;
    }

    if ($someOtherParameter !== 0) {
        return;
    }

    // do the actual work
}

You may be tempted to rewrite combine that if statement.

if ($someParameter !== 0 || $someOtherParameter !== 0) {

In most cases, I don't do this for three reasons:

  1. Personally, I need more brainpower to parse this.
  2. It's easy to make mistakes (should I use || or &&) when there are more conditions
  3. Using early returns is easier to debug. You could put a breakpoint or dump statement inside those if blocks. That way, you know which condition causes an early return.

This post summarised: whenever you see some code executed within an if block, check if you can reverse the condition to lose a level of indentation.

💖 💪 🙅 🚩
freekmurze
Freek Van der Herten

Posted on March 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related