In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, a guard is a
Boolean expression
In computer science, a Boolean expression (also known as logical expression) is an expression used in programming languages that produces a Boolean value when evaluated. A Boolean value is either true or false. A Boolean expression may be compos ...
that must evaluate to true if the
execution
Capital punishment, also known as the death penalty and formerly called judicial homicide, is the state-sanctioned killing of a person as punishment for actual or supposed misconduct. The sentence ordering that an offender be punished in ...
of the
program is to continue in the branch in question. Regardless of which
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
is used, a guard clause, guard code, or guard statement is a check of integrity
precondition
In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification.
If a precondition is violated, the effect of the ...
s used to avoid errors during execution.
The term guard clause is a
Software design pattern
In software engineering, a software design pattern or design pattern is a general, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted directly into s ...
attributed to
Kent Beck who codified many often unnamed coding practices into named software design patterns, the practice of using this technique dates back to at least the early 1960's. The guard clause most commonly is added at the beginning of a procedure and is said to "guard" the rest of the procedure by handling edgecases upfront.
Uses
A typical example is checking that a
reference
A reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''nam ...
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)
Flatter code with less nesting
The guard provides an
early exit from a
subroutine
In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-defined interface and behavior and can be invoked multiple times.
Callable units provide a ...
, and is a commonly used deviation from
structured programming Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making specific disciplined use of the structured control flow constructs of selection ( if/then/else) and repet ...
, 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 makes it easier to read and reason about
def f_guard(x):
if not isinstance(x, int):
return None
#code
#code
#code
return x + 1
Another example, written in
C:
// This function has no guard clause
int funcNoGuard(int x)
// Equivalent function with a guard clause
int funcGuard(int x)
Terminology
The term is used with specific meaning in
APL,
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
,
Clean,
Erlang,
occam,
Promela,
OCaml
OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
,
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIF ...
,
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
In computer science, formal methods are mathematics, mathematically rigorous techniques for the formal specification, specification, development, Program analysis, analysis, and formal verification, verification of software and computer hardware, ...
. Guards can be used to augment
pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually must be exact: "either it will or will not be a ...
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 first to pass is chosen. Guards in a list of cases are typically parallel.
However, in Haskell
list comprehensions the guards are in series, and if any of them fails, the list element is not produced. This would be the same as combining the separate guards with
logical AND
In logic, mathematics and linguistics, ''and'' (\wedge) is the truth-functional operator of conjunction or logical conjunction. The logical connective of this operator is typically represented as \wedge or \& or K (prefix) or \times or \cdo ...
, except that there can be other list comprehension clauses among the guards.
Evolution
A simple conditional expression, already present in
CPL in 1963, has a guard on first sub-expression, and another sub-expression to use in case the first one cannot be used. Some common ways to write this:
(x>0) -> 1/x; 0
x>0 ? 1/x : 0
If the second sub-expression can be a further simple conditional expression, we can give more alternatives to try before the last ''fall-through'':
(x>0) -> 1/x; (x<0) -> -1/x; 0
In 1966
ISWIM had a form of conditional expression without an obligatory fall-through case, thus separating guard from the concept of choosing either-or. In the case of ISWIM, if none of the alternatives could be used, the value was to be ''undefined'', which was defined to never compute into a value.
KRC, a "miniaturized version" of
SASL (1976), was one of the first programming languages to use the term "guard". Its function definitions could have several clauses, and the one to apply was chosen based on the guards that followed each clause:
fac n = 1, n = 0
= n * fac (n-1), n > 0
Use of guard clauses, and the term "guard clause", dates at least to
Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
practice in the 1990s, as codified by
Kent Beck.
[
In 1996, Dyalog APL adopted an alternative pure functional style in which the guard is the only control structure.] This example, in APL, computes the parity of the input number:
parity←{
2∣⍵ : 'odd'
'even'
}
Pattern guard
In addition to a guard attached to a pattern, pattern guard can refer to the use of pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually must be exact: "either it will or will not be a ...
in the context of a guard. In effect, a match of the pattern is taken to mean pass. This meaning was introduced in a proposal for Haskell by Simon Peyton Jones title
A new view of guards
in April 1997 and was used in the implementation of the proposal. The feature provides the ability to use patterns in the guards of a pattern.
An example in extended Haskell:
clunky env var1 var2
, Just val1 <- lookup env var1
, Just val2 <- lookup env var2
= val1 + val2
-- ...other equations for clunky...
This would read: "Clunky for an environment and two variables, ''in case the lookups of the variables from the environment produce values'', is the sum of the values. ..." As in list comprehensions, the guards are in series, and if any of them fails the branch is not taken.
See also
* Assertion
* Guarded Command Language, a programming language based on non-deterministic conditionals
* Guarded suspension
* Iverson bracket
* Logical conditional
Logic is the study of correct reasoning. It includes both formal and informal logic. Formal logic is the study of deductively valid inferences or logical truths. It examines how conclusions follow from premises based on the structure of ...
* Sentinel node, an object to represent the end of a data structure
* Switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function ...
References
{{Reflist
External links
Guard
in ''Free On-Line Dictionary of Computing - FOLDOC'', Denis Howe (editor).
Guard Clause
WikiWikiWeb
The WikiWikiWeb is the first wiki, or user-editable website. It was launched on 25 March 1995 by programmer Ward Cunningham and has been a read-only archive since 2015. The name ''WikiWikiWeb'' originally also applied to the wiki software that o ...
* ''The Haskell 98 Report'', chapte
3 Expressions
* ''The Mathematica Book,'' sectio
2.3.5 Putting Constraints on Patterns
* ''The Glorious Glasgow Haskell Compilation System User's Guide'', Version 6.4, sectio
Conditional constructs
Formal methods terminology
Articles with example Haskell code