Let's first look at a common way to write conditions:
// Without function encapsulation
if (state === "fetching" && isEmpty(itemsList)) {
// ...
}
This code has several problems:
- You need to read and understand the logic inside the if statement
- If you need this check in other places, you'll likely copy-paste it
- Adding new conditions makes the if statement longer and harder to read
Here's a better approach:
function shouldShowSpinner(state, itemsList) {
return state === "fetching" && isEmpty(itemsList);
}
if (shouldShowSpinner(currentState, currentItemsList)) {
// ...
}
This approach brings 4 main benefits:
Better readability: Instead of reading through the logic inside the if statement, you can understand what the code does by reading the function name
shouldShowSpinner
.Code reuse: You can use the same condition in different parts of your code by calling the function, avoiding copy-paste.
Easier maintenance: When you need to change the logic, you only change it in one place - inside the function. For example, if you need to add a new condition:
function shouldShowSpinner(state, itemsList) {
return state === "fetching" &&
isEmpty(itemsList) &&
!hasError(state);
}
- Simpler testing: You can write focused tests for the function to make sure your conditional logic works correctly.
This practice works best for conditions that:
- Have multiple parts
- Need to be used in several places
- Express an important business rule
- Might change in the future
Start small - look for complex if statements in your code and try putting them into functions with clear names. You'll see how much easier your code becomes to read and maintain.
Top comments (0)