Why is good to check for "false" first in an if statement?

Viewed 1579

For example the following code tests for false first then truth. Is there any performance benefits or time saving doing this?

if (!touch('some_file.txt', $time)) {
    echo 'Whoops, something went wrong...';
} else {
    echo 'Touched file with success';
}

instead of

if (touch('some_file.txt', $time)) {
    echo 'Touched file with success';
} else {
    echo 'Whoops, something went wrong...';
}
3 Answers

In fact, checking for "false" is not a question performance, it's a question of Cyclomatic complexity. Let me make it clear: Imagine that you have to get 4 or 5 conditions true before you'd be able to make an action:

if (condition1 === true) {
    ...code

    if (condition2 === true) {
        ...code

        if (condition3 === true) {
            ...code

            if (condition4 === true) {
                ...code

                if (condition5 === true) {
                    ...code
                    return value;
                }
            }
        }
    }
}

This would be get really complicated to understand right ? Now let's apply the "leave early" rule, by checking for "false". The code below does exactly the same thing that does the code above:

if (condition1 === false) {
    return;
}

...code of condition 1 when is true
if (condition2 === false) {
    return;
}


...code of condition 2 when is true
if (condition3 === false) {
    return;
}


...code of condition 3 when is true
if (condition4 === false) {
    return;
}

...code of condition 4 when is true
if (condition5 === false) {
    return;
}

return value;

See how code is much cleaner and EASIER to read ? This is simply because you kept nested levels to the minimum instead of accumulating them.

I hope this answers your question.

You can check on truth first but in main cases you would interact your code if false (for example file doesn't exists so you can put return false in if block.

And if you use if (touch()) you have to write many code in {} block

Compare:

if (touch(file)) {
    //do something...
    // do domething else...
    if (file contensts) {
        //do something....
        //and so on...
        if() {
           // you can continue yourself...
        }
    }
    // continue...
}

and

if (!touch(file)) {
    throw new Error('some error');
    // or return false
}

//do something...
// do domething else...

if (!contents(file)) {
    return false;
}

// continue...

So for stick on one style everyone check on false first

There's no actual performance benefit with having false in the first condition. However, personally I do this as practice to have a cleaner code. Usually if false should terminate the function.

if (!$true)
   return false;

long code...

Instead of having a very long braces that's quite hard to track sometimes.

Related