HOME

TheInfoList



OR:

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
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. 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, structu ...
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 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, multi-paradigm programming language Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. ...
,
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 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, optimiza ...
, 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 exp ...
. 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: f(x) = \left\{ \begin{matrix} 1 & \mbox{if } x>0 \\ 0 & \mbox{otherwise} \end{matrix} \right. 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, 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 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 ...
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 ...
. 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 f ...
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 * Logical conditional *
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 s ...
*
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


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 to accompany the Portland Pattern Repository website discussing software design patterns. The name ''WikiWikiWeb'' ori ...
* ''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