DEV Community

Cover image for Guard Clauses Technique
Roland Dumitrascu
Roland Dumitrascu

Posted on

Guard Clauses Technique

Let’s be honest, how many times you found yourself in situations like this:

void someMethod() {
    if (condition1) {
        if (condition2) {
            if (condition3) {
                doSomething();
            } else {
                debugPrint('Problem 3');
            }
        } else {
            debugPrint('Problem 2');
        }
    } else {
        debugPrint('Problem 1');
    }
}
Enter fullscreen mode Exit fullscreen mode

Countless times, perhaps even worse than that, especially at the beginning of our developer careers. The more conditions you nest, the more your code will get like this:

void someMethod() {
    if (condition1) {
        if (condition2) {
            if (condition3) {
                if (condition4) {
                    if (condition5) {
                        if (condition6) {
                            if (condition7) {
                                if (condition8) {
                                    doSomething();
Enter fullscreen mode Exit fullscreen mode

It can get pretty ugly and make the code reading process very frustrating. There is a better, more intuitive and read-friendly way to do it.

Guard Clauses

A guard clause consists of an expression that must evaluate whether code execution should continue. In a nutshell, instead of nesting multiple if conditions one inside another, we create guard clauses that individually checks if there is a problem before executing the main code. Let’s have a look at the transformation from the example above to the guard clauses technique:

void someMethod() {
    if (!condition1) {
        debugPrint('Problem 1');
        return;
    }
    if (!condition2) {
        debugPrint('Problem 2');
        return;
    }
    if (!condition3) {
        debugPrint('Problem 3');
        return;
    }

    doSomething();
    return;
}
Enter fullscreen mode Exit fullscreen mode

Much more readable right?

Now is much simpler to add new conditions without messing up the code.

For more articles, follow me here on DEV.TO, on Flutter in a Nutshell and Twitter.

Top comments (0)