Daniel Kendell

Tag: You’re doing it wrong

You’re Doing It Wrong: Branches

by Daniel on Nov.19, 2008, under Programming, Soapbox

A fairly straightforward thing you’d think. And you’d be right. But consider the following example.

if ( isset( $a ) )
{
    if ( isset( $b ) )
    {
        if ( isset( $c ) )
        {
            echo $a, ' - ', $b, ' - ', $c;
        }
        else
        {
            die( 'need $c' );
        }
    }
    else
    {
        die( 'need $b' );
    }
}
else
{
    die( 'need $a' );
}

As you can see, the actual operation here is the echo, and it’s nested three levels deep. If it were in a class method, then it’s still three levels deep, but it’s tabbed across the screen five times already.

Imagine this was a far more complicated piece of code and and it was a good four or five “screenfuls” it starts getting a bit challenging keeping track of all the different levels of branches and where you are in them. You end up doing a lot of scrolling up and down to remind yourself.

Why not adopt a “return-early” coding style instead? You check for what would stop your code working as opposed to what it needs to work. The above example has been rewritten to return-early style instead and now the echo statement isn’t in any branches at all.

if ( !isset( $a ) )
{
    die( 'need $a' );
}

if ( !isset( $b ) )
{
    die( 'need $b' );
}

if ( !isset( $c ) )
{
    die( 'need $c' );
}

echo $a, ' - ', $b, ' - ', $c;

What you have now is three small branches or chunks of code on screen that can be modified and rearranged a lot easier than they would be if you had multiple nested branches.

I guess the moral of the story is to keep as much of your code as far left of the screen as you can.

Leave a Comment :, more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!