Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing If Else unique conditional nested statements

Switch case statements are good to replace nested if statements if we have the same condition but different criteria. But what is a good approach if those nested if statements all have different and unique conditions? Do I have any alternate options to replace a dozen if else statements nested inside each other?

Sample Code:

  • Note: I know this is extremely unreadable - which is the whole point.
  • Note: All conditions are unique.

...

if (condition) {
    // do A
} else {                       
    if (condition) {
        // do B
    if (condition) {
        if (condition) {
            if (condition) {
                // do C
                if (condition) {
                    // do D
                    if (condition) {
                        // do E
                    } else {                                                   
                        if (condition) {
                            // do F
                        }
                    }
                }
            }

            if (condition) {
                // do G
                if (condition) {
                    // do H
                    if (condition) {
                        // do I
                    } else {
                        // do J
                    }
                }
            }
        }
    }
}

like image 387
EP2012 Avatar asked Nov 08 '12 22:11

EP2012


People also ask

Which of the following can replace the multiple if conditions in C#?

You can use switch statement instead of multiple if statements.


1 Answers

The best approach in this case is to chop up the thing into appropriately named separate methods.

like image 166
Tar Avatar answered Oct 02 '22 20:10

Tar