Skip to content
Kenny Pflug edited this page Nov 9, 2018 · 2 revisions

What exactly is a Guard Clause?

On his website refactoring.com, Martin Fowler describes Guard Clauses to be a solution for a method having "conditional behavior that does not make clear what the normal path of execution is". His original Java example can be translated to C# in the following way:

Method with convoluted branching logic:

public double GetPayAmount() {
  double result;
  if (_isDead) result = DeadAmount();
  else {
    if (_isSeparated) result = SeparatedAmount();
    else {
      if (_isRetired) result = RetiredAmount();
      else result = NormalPayAmount();
    };
  }
  return result;
}  

This can be refactored to:

public double GetPayAmount() {
  if (_isDead) return DeadAmount();
  if (_isSeparated) return SeparatedAmount();
  if (_isRetired) return RetiredAmount();
  return NormalPayAmount();
};  

As you can see, the branching logic was simplified by using if statements that immediately return if they apply, which is way easier to grasp for our developer brains. It's also interesting that these Guard Clauses do not throw exceptions - thus a Guard Clause's purpose is not necessarily to stop program execution when a passed-in parameter is invalid.

However, most Guard Clauses you'll see in your day-to-day life as a software developer will throw exceptions. This is because their intention is to act as a precondition (or invariant) check. These were first described in Bertrand Meyer's excellent book Object Oriented Software Construction as part of his Design by Contract mechanism.

In short, Design by Contract is implemented via Boolean assertions. These assertions can express

  • Preconditions: these check that parameter values of a method are valid
  • Postconditions: these check that the return value(s) / side effects of a method are valid
  • Class Invariants: these check that an object's state is never invalid (at stable moments of the object's lifetime)
  • Loop Invariants and Variants: these check the correctness of loops by checking what is allowed to change during loop runs

In his very own programming language Eiffel, Design by Contract is deeply integrated. E.g. at the beginning and end of methods, you can write pure statements (no side effects allowed) returning a Boolean value. These statements are executed (if selectively compiled) by the Eiffel runtime which automatically throws an exception when one of these assertions returns false:

Example for pre- and postconditions in Eiffel

So there you have it: a Guard Clauses as we understand it today is essentially a precondition or invariant check at the beginning of your methods that protects the actual functionality of your method from executing unless all corresponding values are valid.