Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor if-else-if structure

How can I refactor the following C++ code? I am using C++11 in my program

void f(int a, int b, int c, int d, int e, int f) {

  // MAX1..MAX6 are constants, N1..N6 are constants
    if( a > MAX1) {
        .. code block 1..
    }
    else if(b > MAX2) {
        .. code block 2..
    }
    else if(c > MAX3) {
        .. code block ..
    }
    else if(d > MAX4) {
        .. code block 3 ..
    }
    else if(e > MAX5) {
        .. code block 4 ..
    }
    else if(f > MAX6) {
        .. code block5 ..
    }
    else if(( a > N1) && ( b > N2)) {
            .. code block 6 ..
    }
    else if(( c > N3) && ( d > N4)) {
            .. code block 7 ..
    }
    else if (( e > N5) && ( f > N6)) {
            .. code block 8 ..
    }
    else if (( a > N1) && ( b > N2) && (d > N4)) {
            .. code block 9 ..
    }
    else if (..some combination of (a > N1) to (f > N6)...) {
            // there are more than 30 such combinations in my code
            .. code block XX ..
    }
    else {
            .... code block ....
    }
like image 398
John Qualis Avatar asked Sep 18 '13 16:09

John Qualis


People also ask

How do you refactor multiple ifs?

So, how do you refactor multiple nested if statements? The easiest possible way is to use guard clauses. A guard clause is an if statement that checks for a condition and favors early exit from the current method. If the condition is satisfied, the if block returns from the method.

What structure is if else?

The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.


1 Answers

There will be at most 64 code blocks in the function, each of which can use an anonymous function, or a named one:

my_func_array[64] = {
    [CONDITION(1,0,0,0,0,0)] = { codeblock1 },
    [CONDITION(0,1,0,0,0,0)] = { codeblock2 },
     ...
};

The macro will basically concatenate the 6 first inputs to an index, essentially translating into:

 my_func_array[64] = {
    [32] = { ... },
    [16] = { ... },
 };

meaning that you don't have to input the conditions in any particular order...

When running, you have to also evaluate all the conditions:

 int condition = CONDITION(a < MAX1, b < MAX2, c < MAX2, ...);
 if (my_func_array[condition])
      my_func_array[condition]();
 else
 {
      // this second block should cover all the other cases
      int condition2 = CONDITION(a < N1, b < N2, c < N3, ... );
      if (my_func_array2[condition2])
          my_func_array2[condition2]();
 }
like image 140
Aki Suihkonen Avatar answered Oct 05 '22 03:10

Aki Suihkonen