Hello! Today, let’s discuss how to handle complex if statements in our code.
Imagine we are reading a codebase we are not yet familiar with. This is the codebase for a coffee shop system. We come across the following piece of code1:
The number of conditions and the nested levels in the if
statement make the code very hard to read and understand. To improve the readability of the code, we can create dedicated variables for each condition:
This refactoring significantly improves readability. By breaking down the conditions into meaningful variable names, we reduce the cognitive load required to understand what the code does. Additionally, debugging this code becomes much easier.
Yet, while this new version is more readable, the set of conditions takes seven lines, which can be distracting if the reader is skimming the code. A more concise approach is to abstract this logic into a dedicated function:
This version encapsulates the logic in a function with a single and clear goal: checking whether the notification matches the user. This reduces distractions for readers and makes the code more concise and easy to read.
NOTE: One could also challenge whether a function with six parameters is also hard to read and could lead to mistakes such as mixing two adjacent parameters of the same type (e.g.,
orderID
andcustomerID
). We will explore the topic of function design in a future issue.
Refactoring complex if
statements by breaking them into well-named variables or abstracting them into functions can significantly enhance our code readability and maintainability. As a rule of thumb, we may want to consider simplifying any if
statement that includes two or more &&
or ||
conditions.
By paying attention to how we structure conditions, we make our code easier to read and work with in the long run.
Tomorrow, let’s discuss the concept of cohesion.
Examples inspired by Don’t use complex expressions in if conditions.