A Case for Guard Clauses

One of my pet peeves in programming is that few people use guard clauses. A guard clause is an almost trivial concept that greatly improves readability. Inside a method, handle your special cases right away and return immediately.

Have a look at the following example:

private int doSomething() {
    if (everythingIsGood()) {

        /*
         * Lots and lots of code here, but that's a different story.
         */

        return SOME_VALUE;
    } else {
        return ANOTHER_VALUE;  // a special case
    }
}

You can easily rewrite it using the Replace Nested Conditional with Guard Clauses refactoring from Martin Fowler’s Refactoring:

private int doSomething() {
    if (! everythingIsGood()) // <-- this is your guard clause
        return ANOTHER_VALUE;

    /*
     * Lots and lots of code here, but that's a different story.
     */

    return SOME_VALUE;
}

Once you’ve read past the conditional(s) at the beginning of the method, you know that your world is in order and you don’t have to worry about special cases anymore.

Explore posts in the same categories: best practices

Tags: , ,

You can comment below, or link to this permanent URL from your own site.

6 Comments on “A Case for Guard Clauses”

  1. panzi Says:

    Good point.

  2. David Linsin Says:

    I think this is related to the notion of “fail-fast”, right? Which I wrote about here: http://dlinsin.blogspot.com/2008/07/how-to-fail-fast-on-faulty-injection.html

  3. mafr Says:

    Yup, it’s definitely related. But catching special cases early can also help to simplify your algorithm, much beyond my trivial example.

  4. Christoph Schmitz Says:

    I think this is a result of the doctrine that every method should have exactly one exit, which has been tought (and might be tought today) in many programming classes.

    While your first example actually has two exits, it’s quite similar to the style that you often see which has one “returnValue” local variable per method and exactly one “return returnValue” statement at the end.

    • Geek Says:

      That’s a valid strategy in C to make sure that all memory and locks allocated is freed again. Newer programming languages provide a garbage collector and synchronization has gotten a part of the language. So it’s not that important any more.

  5. mafr Says:

    @Christoph: Yup. This could perhaps date back to Dijkstra’s “Notes on Structured Programming” from 1969. But if you want to program this way, you should also be forced to provide a correctness proof :)


Comment: