Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing nested if statements

This is related to a chapter from beautiful code. And in that chapter I read about the nested ifs.

The author was talking about deeply nested ifs as originator of bugs and less readable. And he was talking about replacing nested ifs with case statements and decision tables.

Can anybody illustrate how to remove nested ifs with case (select case) and decision tables ?

like image 244
Biswanath Avatar asked Dec 03 '08 13:12

Biswanath


People also ask

What can I use instead of a nested IF statement?

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.

Does IFS replace nested IF?

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.

How do you avoid multiple nested if statements?

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.

What is an alternative to complex nested if statements in Java?

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.


1 Answers

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.

like image 67
Lasse V. Karlsen Avatar answered Sep 22 '22 17:09

Lasse V. Karlsen