Encountering the Problem
What is nested logic? What problems does it bring? For example, consider a practical case: “validating user input.” To achieve this, input checks are necessary, such as checking if the input is empty, checking if it meets the criteria, checking for any possible error scenarios, etc.
function signupUser(username, password, passwordConfirmation) { if (username === '') { return 'Username is required'; } else { if (password === '') { return 'Password is required'; } else { if (password !== passwordConfirmation) { return 'Password confirmation does not match'; } else { return 'Proceeding with registration'; } } }}
The current issue is that the nesting level is too deep, making the code hard to read and maintain! Let’s try rewriting this code using guard clauses:
function signupUser(username, password, passwordConfirmation) { if (username === '') { return 'Username is required'; }
if (password === '') { return 'Password is required'; }
if (password !== passwordConfirmation) { return 'Password confirmation does not match'; }
return 'Proceeding with registration';}
By changing the thought process (returning early to terminate the function), we can achieve better readability and reduce nesting levels.
Conclusion
If you need more than 3 levels of nesting, you’ve messed up and should consider refactoring your code.
The reason for so much nesting is that our thought process is “check for errors first, then execute the normal flow,” but this makes the code hard to read. Therefore, we can change our thought process to return the negative conditions first, which is the concept of guard clauses. Finally, here are two ways to eliminate nesting:
Inversion
Returning abnormal states early allows us to focus more on the Happy Path (normal flow) and easily modify and understand the logic as requirements grow.
Encapsulation
If the code is too complex, consider extracting segments into a separate function, making the code clearer and more focused.
References
- Why You Shouldn’t Nest Your Code - Code Aesthetic
- Replace Nested Conditional with Guard Clauses - REFACTORING GURU
- Why I Don’t Use Else When Programming - Web Dev Simplified