Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Guard (computer science)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== 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:<ref name="beck">{{cite book |title=Smalltalk Best Practice Patterns, |first=Kent |last=Beck |authorlink=Kent Beck |year=1997 |section=Guard Clause |pages=178β179}}</ref> replacing <code>if guard { ... }</code> with <code>if not guard: return; ...</code>. 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 (programming language)|Python]]: <syntaxhighlight lang="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 </syntaxhighlight> Another example, written in [[C (programming language)|C]]: <syntaxhighlight lang="c"> // This function has no guard clause int funcNoGuard(int x) { if (x >= 0) { //code //code //code return x + 1; } else { return 0; } } // Equivalent function with a guard clause int funcGuard(int x) { if (x < 0) { return 0; } //code //code //code return x + 1; } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)