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. Uses 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.public string Foo(string username) { if (username == null) { throw new ArgumentNullException(nameof(username), "Username is null."); } // Rest of the method code follows here... } Flatter code with less nesting 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: replacing if guard { ... } with if not guard: return; .... Using guard clauses can be a refactoring technique to improve code. In general, less nesting is good, as it simplifies the code and reduces cognitive burden. For example, in Python: # This function has no guard clause def f_noguard(x): if isinstance(x, int): #code #code #code return x + 1 else: return None # Equivalent function with a guard clause. Note that most of the code is less indented, which is good def f_guard(x): if not isinstance(x, int): return None #code #code #code return x + 1 Terminology The term is used with specific meaning in APL, Haskell, Clean, Erlang, occam, Promela, OCaml, Swift, Python from version 3.10, and Scala programming languages. 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. Mathematics 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: In this case the guards are in the "if" and "otherwise" clauses. Multiple guards If there are several parallel guards, they are normally tried in a top-to-bottom order, and the branch of the