tags:

views:

77

answers:

4

Is one of the following functions better than the other, in terms of where to place the 'return false' statement?

Function #1:

function equalToTwo($a, $b)
{
    $c = $a + $b;
    if($c == 2)
    {
        return true;
    }
    return false;
}

Function #2:

function equalToTwo($a, $b)
{
    $c = $a + $b;
    if($c == 2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Thanks!

+9  A: 

There is no functional difference between the two; you should choose whichever one is most obvious and readable.

I would usually use an else.

Note that your particular example should be written as

return $c == 2;
SLaks
Good point. Do not be afraid of using comparison operators outside control structures. Booleans are values too!
Matti Virkkunen
@SLaks: I am accepting your answer because you answered the question AND provided an alternative, which, in my opinion, is a lot nicer!
letseatfood
Thanks​​​​​​​​!
SLaks
A: 

There is no difference between them. In my opinion they're both equally readable, and there is no noticeable performance different either.

Matti Virkkunen
+2  A: 

What about just:

return ($c == 2);
dreamlax
+2  A: 

In this case choose whichever is more easily readable for you, since it's such a small function.

In cases where the function is much larger it's usually best to do something like this...

function do( $var=null ) {

    if ( $var === null ) {
        return false;
    }

    // many lines of code

}

In this case it would matter. Fail right away. Because it is much more readable than...

function do( $var=null ) {

    if ( $var !== null ) {
        //many lines of code
    }
    else {
        return false;
    }

}
Galen
@Galen: Thanks, this is informative.
letseatfood