Guard Clause Considered Helpful

Apparently, PragDave recently questioned the conventional wisdom about GOTO considered harmful (does this mean all “X considered harmful” articles will be retrospectively struck off the record?). Ivan Moore’s given an example as to why the rule of “a single exit point” sucks, and I agree.

Another reason for multiple exit points is guard clauses. Code units, like classes or functions, ought to look right at a high level. Just like with a piece of writing, it’s important that the overall structure gives you the big picture. Guard clauses help here. You can say, “Okay, let’s get the cruft out of the way – the trivial cases, the exception cases – and now we can focus on the main thing the function’s meant to do.”

  1. void foo() {
  2.   if (nothingToDo) { return; }
  3.   // Implement typical behaviour of foo()
  4. }

is much more readable than:

  1. void foo() {
  2.   if (!nothingToDo()) { // Hold my breath until the end
  3.     // *ugh* The typical behaviour buried in an if-clause
  4.     // And adding insult, we're now indenting more than we need to
  5. }

Steve Freeman points out, Ivan’s particular example could be refactored nicely into a single ternary operator statement. While they don’t scale to larger, more complex, functions, ternary operators are a very handy tool for the reason he explains.

One thought on “Guard Clause Considered Helpful

  1. The single exit point is one of the code review comments in software engineering. And despite of knowing the stuff about the guard clause and making the code more readable, code reviewer keeps giving this comments.

    Is there a way to convince them?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>