In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question.
Regardless of which programming language is used, a guard clause, guard code, or guard statement, is a check of integrity preconditions used to avoid errors during execution. A typical example is checking that a reference about to be processed is not null, which avoids null-pointer failures. Other uses include using a boolean field for idempotence (so subsequent calls are nops), as in the dispose pattern. The guard provides an early exit from a subroutine, and is a commonly used deviation from structured programming, removing one level of nesting and resulting in flatter code:[1] replacing if guard { ... }
with if not guard: return; ...
. For example, in Python:
# This function has no guard clause
def f_noguard(x):
if isinstance(x, int):
return x + 1
# Equivalent function with a guard clause
def f_guard(x):
if not isinstance(x, int):
return None
return x + 1
The term is used with specific meaning in APL, Haskell, Clean, Erlang, occam, Promela, OCaml, Swift,[2]Python from version 3.10, and Scala programming languages.[citation needed] In Mathematica, guards are called constraints. Guards are the fundamental concept in Guarded Command Language, a language in formal methods. Guards can be used to augment pattern matching with the possibility to skip a pattern even if the structure matches. Boolean expressions in conditional statements usually also fit this definition of a guard although they are called conditions.
In the following Haskell example, the guards occur between each pair of “|” and “=”:
f x
| x > 0 = 1
| otherwise = 0
This is similar to the respective mathematical notation: