Skip to content

Guard clauses

Checking that preconditions hold before executing the logic. One form of tidying.

For example, changing this code…

if (condition0)
	if (!condition1)
		doSomething()

…into this.

if (!condition0) return
if (condition1) return

doSomething()

However, if a routine has more than seven or eight guards, a different intervention may be needed.

Meanwhile, on the claim that a function should have only one return:

The “rule” about having a single return for a routine came from the days of FORTRAN, where a single routine could have multiple entry and exit points. It was nearly impossible to debug such code. You couldn’t tell what statements were executed. Code with guard clauses is easier to analyze because the preconditions are explicit. —Tidy first? A personal exercise in empirical software design

Swift

Swift explicitly supports guards.

guard condition else {
  statements
}

TypeScript

In TypeScript, user-defined type predicates and type guards can assist type inference.1

Footnotes

  1. typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

Created
Updated

Machine-translated from the Korean original.

2026 © ak | markdown | 한국어