Guard clause

A Guard Clause (one of the SmalltalkBestPracticePatterns, and equally applicable in a whole bunch of languages) is a chunk of code at the top of a function (or block) that serves a similar purpose to a Precondition.

It typically does one (or any or all) of the following:

  • checks the passed-in parameters, and returns with an error if they’re not suitable.
  • checks the state of the object, and bails out if the function call is inappropriate.
  • checks for trivial cases, and gets rid of them quickly.

For example:

draw() {
  if (! isVisible()) return;
  ...
}

// without Guard Clause
function getPayAmount() {
  let result;
  if (isDead)
    result = deadAmount();
  else {
    if (isSeparated)
      result = separatedAmount();
    else {
      if (isRetired)
        result = retiredAmount();
      else
        result = normalPayAmount();
    }
  }
  return result;
}

// with Guard Clause
function getPayAmount() {
  if (isDead) return deadAmount();
  if (isSeparated) return separatedAmount();
  if (isRetired) return retiredAmount();
  return normalPayAmount();
}

Leave a Reply

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