How to refactor complex if-statements

In this video, which is a part of the Mailcoach video course, Freek shows us how he refactors a complex if-statement.

A technique which I nowadays also like using myself – especially in a React Component’s render method – is to use early returns: instead of nesting if-statements and using else-statements, the function body uses singular if-statements which abort the function’s execution early on in case some condition is/isn’t met. Like so:

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

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

    // do the actual work
}

💡 If you’re a PHP developer I’d recommend the video course to you as it contains some pretty good stuff, such as this video on Pending Objects for example.

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.