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.
Tags: best practices, opinion, quality
You can comment below, or link to this permanent URL from your own site.
June 12, 2009 at 16:16
Good point.
June 12, 2009 at 18:18
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
June 12, 2009 at 19:04
Yup, it’s definitely related. But catching special cases early can also help to simplify your algorithm, much beyond my trivial example.
June 13, 2009 at 09:04
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.
June 30, 2009 at 04:07
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.
June 13, 2009 at 09:22
@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 :)