Guard clauses
“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, guard code or a guard clause is a check of integrity preconditions used to avoid errors during execution.”
— Wikipedia
Let’s take a look at an example. We have a function, getValidCandidate
, which checks if a candidate is valid, provided a list of members and returns the member if the candidate is valid, or undeļ¬ned
otherwise.
Look how nested the code is? Ifs wrapping other ifs, nested 3 times. Let’s rewrite this and use guard clauses instead.
Guard clauses prevent the function from continuing what it’s doing and instead returning early if the guarding condition is not met. Naturally, we also know that the end result is the last return of the function.
Skip the ‘else’ part
Whenever you’re about to write else, stop and reconsider what you’re doing and search for an alternative way to express the logic.
Let’s cover a few ways that we can avoid using else. One of them is guard clauses, which we just covered above. Another approach is using default values. Let’s take an example.
Let’s say we have a function, negateOdd, which takes a number and negates it if the number is odd.
The function does what it’s supposed to. But it’s unnecessarily using an else. Let’s refactor it, and instead, use a default value.
We now assign result with a default value, and the variable will only be changed if the condition in the if-statement is met. But let’s do even better. We’re supposed to question the use of let and imperative (altering the state of your program step by step) code. Let’s see if we can make this function even more readable and concise.
There is a version of if-else that is generally accepted. It’s the ternary operator.
0 comments:
Post a Comment