Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Guard (computer science)

From Wikipedia, the free encyclopedia
Concept in computer science

Incomputer programming, aguard is aBoolean expression that must evaluate to true if theexecution of theprogram is to continue in the branch in question. Regardless of whichprogramming language is used, aguard clause,guard code, orguard statement is a check of integritypreconditions used to avoid errors during execution.

The termguard clause is aSoftware design pattern attributed toKent 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 1960s. Theguard clause most commonly is added at the beginning of a procedure and is said to "guard" the rest of the procedure by handling edge cases upfront.

Uses

[edit]

A typical example is checking that areference about to be processed is not null, which avoidsnull-pointer failures.

Other uses include using a Boolean field foridempotence (so subsequent calls arenops), as in thedispose pattern.

publicStringfoo(Stringusername){if(username==null){thrownewIllegalArgumentException("Username is null.");}// Rest of the method code follows here...}

Flatter code with less nesting

[edit]

The guard provides anearly exit from asubroutine, and is a commonly used deviation fromstructured programming, removing one level of nesting and resulting in flatter code:[1] replacingif guard { ... } withif not guard: return; ....

Using guard clauses can be arefactoring technique to improve code. In general, less nesting is good, as it simplifies the code and reduces cognitive burden.

For example, inPython:

fromtypingimportAny,Optional# This function has no guard clausedeff_noguard(x:Any)->Optional[int]ifisinstance(x,int):# code herereturnx+1else:returnNone# Equivalent function with a guard clause. Note that most of the code is less indented, which makes it easier to read and reason aboutdeff_guard(x:Any)->Optional[int]ifnotisinstance(x,int):returnNone# code herereturnx+1

Another example, written inC:

// This function has no guard clauseintfuncNoGuard(intx){if(x>=0){// code herereturnx+1;}else{return0;}}// Equivalent function with a guard clauseintfuncGuard(intx){if(x<0){return0;}// code herereturnx+1;}

Terminology

[edit]

The term is used with specific meaning inAPL,Haskell,Clean,Erlang,occam,Promela,OCaml,Swift,[2]Python from version 3.10, andScala programming languages.[citation needed] InMathematica, guards are calledconstraints. Guards are the fundamental concept inGuarded Command Language, a language informal methods. Guards can be used to augmentpattern matching with the possibility to skip a pattern even if the structure matches. Boolean expressions inconditional statements usually also fit this definition of a guard although they are calledconditions.

Mathematics

[edit]

In the following Haskell example, the guards occur between each pair of "|" and "=":

fx|x>0=1|otherwise=0

This is similar to the respective mathematical notation:

f(x)={1if x>00otherwise{\displaystyle 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

[edit]

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 Haskelllist 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 withlogical AND, except that there can be other list comprehension clauses among the guards.

Evolution

[edit]

A simple conditional expression, already present inCPL 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; 0x>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 lastfall-through:

(x>0) -> 1/x; (x<0) -> -1/x; 0

In 1966ISWIM 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 beundefined, which was defined to never compute into a value.

KRC, a "miniaturized version"[3] ofSASL (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:

facn=1,n=0=n*fac(n-1),n>0

Use of guard clauses, and the term "guard clause", dates at least toSmalltalk practice in the 1990s, as codified byKent Beck.[1]

In 1996, Dyalog APL adopted an alternative pure functional style in which the guard is the only control structure.[4] This example, in APL, computes the parity of the input number:

parity{2:'odd''even'}

Pattern guard

[edit]

In addition to a guard attached to a pattern,pattern guard can refer to the use ofpattern matching 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 bySimon Peyton Jones titledA 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:

clunkyenvvar1var2|Justval1<-lookupenvvar1,Justval2<-lookupenvvar2=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 inlist comprehensions, the guards are in series, and if any of them fails the branch is not taken.

See also

[edit]

References

[edit]
  1. ^abBeck, Kent (1997). "Guard Clause".Smalltalk Best Practice Patterns,. pp. 178–179.
  2. ^Cook, Nate."guard & defer".NSHipster. Retrieved2016-02-26.
  3. ^Turner, D. A."Some History of Functional Programming Languages"(PDF).
  4. ^Scholes, John."Direct Functions in Dyalog APL"(PDF).

External links

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Guard_(computer_science)&oldid=1323027331"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp