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.

social