Avoiding Deep Nesting
Learn how to avoid deep nesting in code.
We'll cover the following...
Avoiding deep nesting
An important thing we should consider is avoiding deep nesting when it comes to control structures, such as conditional and loop statements.
It’s sometimes tempting to put several if statements or for loops inside each other. But many levels of nested if statements or for loops can make them hard to read and understand.
Take a look at the following code:
function calculate_pay(age)if age > 65 thenresult = 25000elseif age > 20 thenresult = 20000elseresult = 15000end_ifend_ifreturn resultend_function
Here, we have an if statement and in its else part, we have a new if statement with an else part. This is unnecessarily complex and hard to follow. We can rewrite it like this:
function calculate_pay(age)if age > 65 thenreturn 25000if age > 20 thenreturn 20000return 15000end_function
The two functions will give us the same result, but the second one will return as soon as it knows the correct amount. By doing that, it reduces the number of lines, avoids the nested if statement, and overall makes the code cleaner and easier to read.
When you have nested structures ...