Avoiding Deep Nesting

Learn how to avoid deep nesting in code.

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:

Press + to interact
function calculate_pay(age)
if age > 65 then
result = 25000
else
if age > 20 then
result = 20000
else
result = 15000
end_if
end_if
return result
end_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:

Press + to interact
function calculate_pay(age)
if age > 65 then
return 25000
if age > 20 then
return 20000
return 15000
end_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 ...