Guard Clauses

Another interesting topic are Guard clauses as outlined in Michael Mahemoff’s Guard Clause Considered Helpful. Here’s my take on this topic:

How about rephrasing

void foo() {
 if (nothingToDo) { return; }
   // Implement typical behaviour of foo()
}

not like

void foo() {
  if (!nothingToDo()) { 
   // Implement typical behaviour of foo()
  }
}

but like

void foo() {
  if (someThingToDo()) { 
   // Implement typical behaviour of foo()
  }
}

The latter version avoids the double negative (thus concentrating on the standard case and not the exception), and I consider it quite readable in practice, e.g. if (resourceAvailable()) doSomeThing(). However, this will only be a viable alternative to the guard clause if foo() is very short. If foo() get’s so long that using the guard clause seems appropriate because the function will be more readable, maybe it’s time to take a long hard look at foo() to search for refactoring opportunities. Avoiding guard clauses may help in detecting functions which got out of control in terms of length & complexity – because there’s an awful lot of “intended code” in the function.

In the end, it boils down to personal preferences. Guard clauses are probably fine as long as the length & complexity of the function is monitored closely.