Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested redundant 'if' conditions

Is there a better (or cleaner) way to write the following code?

if(conditionX) {     if(condition1)     {         // code X1     }     else if(condition2)     {         // code X2     } } else if(conditionY) {     if(condition1)     {         // code Y1     }     else if(condition2)     {         // code Y2     } } 

I have a few more conditions, but I guess you get the point.

like image 512
HAL Avatar asked Mar 18 '14 12:03

HAL


People also ask

How many nested if statements is too many?

Remarks. While Excel will allow you to nest up to 64 different IF functions, it's not at all advisable to do so.

How avoid nested IF?

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.


1 Answers

There are four approaches to this problem, none of which is universal:

  1. Leave everything as is - There isn't much code duplication here. If computing condition1 and condition2 is tricky, compute them upfront and store them in bool variables
  2. Make conditionX and conditionY produce a result that lets you unify condition1 and condition2 - This is not always possible, but in some situations you could prepare a variable that unifies the activities taken in the two branches, say, by using a function pointer or a lambda.
  3. Put the processing logic into subclasses with virtual functions to eliminate conditional logic - This is possible only when your initial design missed an opportunity to subclass. Essentially, this approach pushes the decision on conditionX/conditionY into a place where a subclass is created, and then "reuses" that decision later on by calling a proper override of a virtual function in the interface.
  4. Create a numeric combination representing all three conditions, and convert to switch - This trick unifies the conditionals, reducing the nesting.

Here is an example of the last approach:

int caseNumber = ((conditionX?1:0) << 3)                | ((conditionY?1:0) << 2)                | ((condition2?1:0) << 1)                | ((condition1?1:0) << 0); switch (caseNumber) {     case 0x09:     case 0x0D:     case 0x0F: // code X1         break;     case 0x0A:     case 0x0E: // code X2         break;     case 0x05:     case 0x07: // code Y1         break;     case 0x06: // code Y2         break; } 
like image 89
Sergey Kalinichenko Avatar answered Sep 19 '22 03:09

Sergey Kalinichenko