Bad Coding Style (I)

By | February 12, 2018

Look at the following PHP code snipped. It's a function which calculates the product of its two arguments and returns the result if both arguments are of type integer. Otherwise the function returns false.

 
function mult ( $x, $y ) {
    if ( is_integer ( $x ) ) {
        if ( is_integer ( $y ) ) {
           $result = $x * $y;
        }
        else {
           $result = false;
        }  
    }
    else {
        $result = false;
    }
    return $result;
} 

So far so good. The function does what it should do, and I have seen a lot of functions written this way, but with much more nested ifs and elses. Almost every modern web application contains functions written like this, where these ifs and elses nested so deep that they reach to the right border in a full width window on a 24" monitor.
But you can write the same function much more readable. Look here:

function mult ( $x, $y ) {

    if ( !is_integer ( $x ) ) 
        return false;

    if ( !is_integer ( $y ) )
       return false;

    return x * y;
}

You can almost always convert nested ifs and elses into single ifs which leave the function immediately if they meet their condition.
Of course, you can write the last example a bit shorter too:

function mult ( $x, $y ) {

    if ( !is_integer ( $x ) || !is_integer ( $y )  ) 
        return false;

    return x * y;
}

But keep the readability in mind! Sometimes the shorter the code the more unreadable it gets:

function mult ( $x, $y ) {
    return is_integer ( $x ) && is_integer ( $y ) ? x*y : false;
}

One thought on “Bad Coding Style (I)

  1. Dwayne Robinson

    Yes, here's a clear example where the "never use multiple returns" damages readability more than it aids. Your second and third rewritings are much clearer than the first code.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *