In computer programming, a guard is a
boolean
Any kind of logic, function, expression, or theory based on the work of George Boole is considered Boolean.
Related to this, "Boolean" may refer to:
* Boolean data type, a form of data with only two possible values (usually "true" and "false" ...
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
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
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 ...
s 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
Idempotence (, ) is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. The concept of idempotence arises in a number of pl ...
(so subsequent calls are nops), as in the
dispose pattern
In object-oriented programming, the dispose pattern is a design pattern for resource management. In this pattern, a resource is held by an object, and released by calling a conventional method – usually called close, dispose, free, release dep ...
.
public string Foo(string username)
Flatter code with less nesting
The guard provides an
early exit
Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
from a
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
, 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 extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
, 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
In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structure ...
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
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 has pioneered a number of programming lang ...
,
Clean,
Erlang,
occam,
Promela
PROMELA (Process or Protocol Meta Language) is a verification modeling language introduced by Gerard J. Holzmann. The language allows for the dynamic creation of concurrent processes to model, for example, distributed systems. In PROMELA models, c ...
,
OCaml
OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
,
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
* SWIFT, ...
,
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
from version 3.10, and
Scala programming languages. In
Mathematica
Wolfram Mathematica is a software system with built-in libraries for several areas of technical computing that allow machine learning, statistics, symbolic computation, data manipulation, network analysis, time series analysis, NLP, optimizat ...
, guards are called ''constraints''. Guards are the fundamental concept in
Guarded Command Language The Guarded Command Language (GCL) is a programming language defined by Edsger Dijkstra for predicate transformer semantics in EWD472. It combines programming concepts in a compact way. It makes it easier to develop a program and its proof hand-in-h ...
, a language in
formal methods
In computer science, formal methods are mathematically rigorous techniques for the specification, development, and verification of software and hardware systems. The use of formal methods for software and hardware design is motivated by the expec ...
. 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 has to be exact: "either it will or will not be ...
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 comprehension
A list comprehension is a Syntax of programming languages, syntactic construct available in some programming languages for creating a list based on existing list (computing), lists. It follows the form of the mathematical ''set-builder notation'' ( ...
s 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 logical conjunction; the ''and'' of a set of operands is true if and only if ''all'' of its operands are true. The logical connective that represents this ...
, 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
ISWIM (acronym for If you See What I Mean) is an abstract computer programming language (or a family of languages) devised by Peter Landin and first described in his article "The Next 700 Programming Languages", published in the Communications o ...
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 an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
practice in the 1990s, as codified by
Kent Beck
Kent Beck (born 1961) is an American software engineer and the creator of extreme programming, a software development methodology that eschews rigid formal specification for a collaborative and iterative design process. Beck was one of the 17 ori ...
.
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 has to be exact: "either it will or will not be ...
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
Simon Peyton Jones (born 18 January 1958) is a British computer scientist who researches the implementation and applications of functional programming languages, particularly lazy functional programming.
Education
Peyton Jones graduated from ...
title
A new view of guardsin 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 comprehension
A list comprehension is a Syntax of programming languages, syntactic construct available in some programming languages for creating a list based on existing list (computing), lists. It follows the form of the mathematical ''set-builder notation'' ( ...
s, the guards are in series, and if any of them fails the branch is not taken.
See also
*
Assertion
*
Logical conditional
Logic is the study of correct reasoning. It includes both formal and informal logic. Formal logic is the science of deductively valid inferences or of logical truths. It is a formal science investigating how conclusions follow from premises ...
*
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 some ...
*
Iverson bracket
In mathematics, the Iverson bracket, named after Kenneth E. Iverson, is a notation that generalises the Kronecker delta, which is the Iverson bracket of the statement . It maps any statement to a function of the free variables in that statement. ...
*
Guarded suspension
References
{{Reflist
External links
Guardin ''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 to accompany the Portland Pattern Repository website discussing software design patterns. The name ''WikiWikiWeb'' origi ...
* ''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