Avoiding IF nesting

Avoiding IF nesting

September 25, 2020

codequality

Today I come to share a little tip to improve the readability of our code. We will achieve this by using guard clauses which will help us avoid this IF nesting.

Examples

Bad ❌

In this example, we can see how and IF nesting appears, in this case, it is a simple example but this can get complicated, with each nesting that is added the code will become less readable and therefore less friendly and less maintainable.

const calculatePercentageHeight = (width, height) => {
    const result = (height * 100) / width
 
    if (!Number.isNaN(result)) {
        if (Number.isInteger(result)) {
            return result
        } else {
            return result.toFixed(2)
        }
    } else {
        return 0
    }
}
 
// use function
calculatePercentageHeight(50, 50) // result 100
calculatePercentageHeight(50, 0) // result 0

Good ✅

Using guard clauses we avoid the nesting of IF conditionals since we will "first control the error cases", and then we will continue with our logic.

const calculatePercentageHeight = (width, height) => {
    const result = (height * 100) / width
 
    if (Number.isNaN(result)) return 0 // guard clause
    if (Number.isInteger(result)) return result // guard clause
 
    return result.toFixed(2)
}
 
// use function
calculatePercentageHeight(50, 50) // result 100
calculatePercentageHeight(50, 0) // result 0

Conclusion

Using guard clauses is good practice to avoid unnecessary ramifications and therefore make your code easier and more readable. If we apply these guidelines we will make our software much more maintainable and friendly.


Thanks for reading me. 😊

Buy Me A Coffee