Guard Clauses - How to Clean up Conditionals
One of the first concepts new developers learn is the if/else statement. If/else statements are the most common way to execute conditional logic. However, complex and nested if/else statements can quickly become a cognitive burden and compromise the readability of a program.
Guard Clauses
Guard Clauses leverage the ability to return early from a function (or continue through a loop) to make nested conditionals one-dimensional. Instead of using if/else chains, we just return early from the function at the end of each conditional block.
func divide(dividend, divisor int) (int, error) {
if divisor == 0 {
return 0, errors.New("Can't divide by zero")
}
return dividend/divisor, nil
}
Error handling in Go naturally encourages developers to make use of guard clauses. When I started writing more JavaScript, I was disappointed to see how many nested conditionals existed in the code I was working on.
Let’s take a look at an exaggerated example of nested conditional logic:
function getInsuranceAmount(status) {
let amount;
if (!status.hasInsurance()) {
amount = 1;
} else {
if (status.isTotaled()) {
amount = 10000;
} else {
if (status.isDented()) {
amount = 160;
if (status.isBigDent()) {
amount = 270;
}
} else {
amount = 0;
}
}
}
return amount;
}
Could be written with guard clauses instead:
function getInsuranceAmount(status) {
if (!status.hasInsurance()) {
return 1;
}
if (status.isTotaled()) {
return 10000;
}
if (!status.isDented()) {
return 0;
}
if (status.isBigDent()) {
return 270;
}
return 160;
}
The example above is much easier to read and understand. When writing code, it’s important to try to reduce the cognitive load on the reader by reducing the number of entities they need to think about at any given time.
In the first example, if the developer is trying to figure out when 270 is returned, they need to think about each branch in the logic tree and try to remember which cases matter and which cases don’t. With the one-dimensional structure offered by guard clauses, it’s as simple as stepping through each case in order.
Related Articles
Slow Is Smooth, Smooth Is Fast - 25% of Our Time Refactoring
Sep 01, 2020 by Lane Wagner - Boot.dev co-founder and backend engineer
My team has been spending less of our “free” time working on bugs and features from the backlog, and more time refactoring our code and tests. As a result, and perhaps somewhat counterintuitively, we’ve noticed a significant increase in our throughput of features and bug fixes.
(Very) Basic Intro to Lattices in Cryptography
Aug 21, 2020 by Lane Wagner - Boot.dev co-founder and backend engineer
Lattice-based cryptography, an important contender in the race for quantum-safe encryption, describes constructions of cryptographic primitives that involve mathematical lattices. Lattices, as they relate to crypto, have been coming into the spotlight recently. In January 2019, Many of the semifinalists in the NIST post-quantum-cryptography competition were based on lattices. Lattice-based cryptography has promising aspects that give us hope for cryptographic security in a post-quantum world.
What is SHA-256?
Jul 08, 2020 by Lane Wagner - Boot.dev co-founder and backend engineer
SHA-2 (Secure Hash Algorithm 2), of which SHA-256 is a part, is one of the most popular hash algorithms around. A cryptographic hash, also often referred to as a “digest”, “fingerprint” or “signature”, is an almost perfectly unique string of characters that is generated from a separate piece of input text. SHA-256 generates a 256-bit (32-byte) signature.
Why is Exclusive Or (XOR) Important in Cryptography?
Jan 18, 2020 by Lane Wagner - Boot.dev co-founder and backend engineer
If you are getting into cryptography, or just trying to understand the fundamentals, you may have noticed that the exclusive or (XOR) operation is used quite often, especially in ciphers. XOR is a simple bitwise operation that allows cryptographers to create strong encryption systems, and consequently is a fundamental building block of practically all modern ciphers. Let’s dive into the details and see what makes XOR so important.