Monday, April 23, 2007

The Case for Guard Clauses

As mentioned in a previous post, an XP pair partner of mine and I would get into debates about Guard Clauses. This is a classic Alligators versus Crocodiles issue.

The idea is, in essence, to return from a method quickly for illegal arguments before hitting the main logic of a method.

Guard clause:

if( a == null ) { return; }
if( b == null ) { return; }
doSomething(a, b);

versus not:

if( a != null && b != null ) {
doSomething(a, b);
} else {
// log error
}

I should probably ask him to "guest host" on this entry, but here's my best, honest attempt to summarize the arguments for guard clauses:

  • It's time to bid the 1980s a fond farewell. Methods do not have to adhere to the rule of "having a single point of return", especially in Java, because methods are much shorter now.

  • Checking for null etc ultimately leads to serious indentation which is hard to read.

  • When done correctly, the guard clauses read like a contract for the method. It's like Checked Exceptions Lite: all the intent without the "propogation" aftertaste.

  • It's a refactoring pattern with a cool name!

So there's the Alligator Assessment... next up: the Crocodile Case.

2 comments:

Anonymous said...

It's a very nice summary, but your example code doesn't do justice to the indentation-hell that often precipitates this discussion. It doesn't make the reader feel the pain of real life -- nothing like a Jane Fonda workout for the eyes: "Feel the burn... OK, now give me ten more indents".

My doctor says diagonal eye movements are bad for the eyes -- anything other than horizontal and vertical movements will cause long-term optical damage %-) and maybe brain damage, too &:-)

M Easter said...

The example code is indeed not the worst-case, but the link provided for Guard Clauses (see entry) does have an exaggerated example of indentation, replete with single statements with no enclosing braces.

My doctor says that multiple return statements are bad for the brain -- unless you part of a parallelized, autonomous collective ;-)