Table of contents
We've all learnt the if/else statements at some point as it is one of the first concepts we learn as new developers.
Why You Should Avoid the If/Else Statement
When writing complex if/else statements things can get messy and what may start off as one set of conditions managed by an if/else block can easily become difficult to manage and compromise the readability of a program when more and more conditions are added
Let's see an example of a complex if/else statement
function getPayAmount(){
let result;
if (isDead){
result = deadAmount();
}
else {
if (isSeparated){
result = separatedAmount();
else {
if(isRetired){
result = retiredAmount();
else
result = normalPayAmount();
}
}
return result;
}
Messy right?
Shows how complex if/else statements can easily become difficult to manage and also compromise the readability of a program
Guard Clauses
Instead of writing if else statements, you can use guard clauses to signal an exit for cases when a block of code should not be executed.
using Guard Clause can reduce the number of lines in your functions, classes and so on..
- Guard Clause makes the code easier to read
Let's see an example of Guard Clause:
Below is a refractored code of the example above;
function getPayAmount(){
if (isDead) return deadAmount();
if(isSeparated) return separatedAmount();
if (isRetired) return retiredAmount();
return normalPaymentAmount();
}
We have refractored our if/else statements using Guard Clause and one of the first thing you would notice is that the number of lines of code reduced from 17 to 9
Plus the readability of our program should not be an issue now
Conclusion
Was this useful?
- Follow me for more post like this so we don't lose track of each other.
- Show your support by leaving lots of reactions.
- Spread the knowledge by sharing it.