This is related to a chapter from beautiful code. And in that chapter I read about the nested if
s.
The author was talking about deeply nested if
s as originator of bugs and less readable. And he was talking about replacing nested if
s with case
statements and decision tables.
Can anybody illustrate how to remove nested if
s with case
(select case
) and decision tables ?
Alternatives to nested IF in Excel To test multiple conditions and return different values based on the results of those tests, you can use the CHOOSE function instead of nested IFs. Build a reference table and a use VLOOKUP with approximate match as shown in this example: VLOOKUP instead of nested IF in Excel.
The IFS function evaluates multiple conditions until it finds the first condition that gives a TRUE result. As the name suggests, it is designed to replace nested IF statements containing multiple IF functions.
Nested IFs are powerful, but they become complicated quickly as you add more levels. One way to avoid more levels is to use IF in combination with the AND and OR functions. These functions return a simple TRUE/FALSE result that works perfectly inside IF, so you can use them to extend the logic of a single IF.
We can also design a Calculator#calculate method to accept a command which can be executed on the inputs. This will be another way of replacing nested if statements.
Well, not directly an answer to your question since you specifically ask about switch/case statements, but here is a similar question.
Invert “if” statement to reduce nesting
This talks about replacing nested if's with guard-statements, that return early, instead of progressively checking more and more things before settling on a return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With