Guard Clauses
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 68 of 78.
When a function needs several checks, nesting one if inside another pushes the real work deeper and deeper:
func buy(gold: int, price: int) -> String:
if price > 0:
if gold >= price:
return "Bought! %d gold left" % (gold - price)
else:
return "Not enough gold"
else:
return "Invalid price"A guard clause turns this around. It checks one invalid case at the top of the function and leaves right away with return. The code after the guards runs only with valid values, and it needs no nesting:
func buy(gold: int, price: int) -> String:
if price <= 0:
return "Invalid price"
if gold < price:
return "Not enough gold"
return "Bought! %d gold left" % (gold - price)buy(50, 30) returns Bought! 20 gold left, buy(10, 30) returns Not enough gold and buy(50, 0) returns Invalid price.
The order of the guards matters: the guard that protects a line must come before it. Check the text with is_valid_int() before you use the number, and check for zero before you divide:
func share(coins: int, players: int) -> int:
if players <= 0:
return 0
return coins / playersIn a -> void function, a guard is return on its own. Inside a loop, continue works as a guard for one element: it skips an invalid element and the loop goes on with the next one.
Challenge
EasyWrite the function process_data. It takes a string text and returns a string:
- If
textis not a whole number, returnInput must be a number! - If the number is
0, returnCannot divide by zero! - Otherwise, divide
100.0by the number and return the result with two decimals
For example, process_data("8") returns 12.50, process_data("-5") returns -20.00 and process_data("abc") returns Input must be a number!.
Write the two checks as guard clauses at the top of the function.
Try it yourself
func process_data(text: String):
# Write code here
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary Sorter12Basic Error Handling
What is Error Handling?Validating InputGuard ClausesReturning Error CodesRecap - Safe DivisionPractice on your own: Online GDScript compiler