Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested switch alternative

While playing with NLP I've been encountered with little problem:

switch(var1)
{
case Variant1_1:
    if( cond1 )
    {
        if( cond2 )
        {
            if( cond3 )
            {
                switch(var2)
                {
                case Variant2_1:
                    return someExpression;
                // another five-six cases
                default:
                    return;
                }
            }
            else // cond3
            {
                switch(var2)
                {
                case Variant2_1:
                    return someExpression;
                // another five-six cases
                default:
                    return;
                }
            } 
        }
        else // cond2
        {
            if( cond3 )
            {
                switch(var2)
                {
                case Variant2_1:
                    return someExpression;
                // another five-six cases
                default:
                    return;
                }
            }
            else // cond3
            {
                switch(var2)
                {
                case Variant2_1:
                    return someExpression;
                // another five-six cases
                default:
                    return;
                }
            } 
        }
    }
    else // cond1
    {
        // same thing

    }
    break;
case Variant1_2:
    // same gigantic tree
    break;
case Variant1_3:
    // here too
    break;
default:
    return;
}

What alternatives are for such "computational tree"? The only thing that comes to my mind - some tree container with function pointers as leaves and a great deal of little functions.

like image 363
MadRunner Avatar asked Apr 28 '26 11:04

MadRunner


2 Answers

(tongue in cheek) Every time you encounter a switch statement in a C++ program, you know that you've missed an inheritance opportunity.

The two ways I know to refactor multiple parallel switches are (1) building a multi-dimension array of function pointers, and (2) using a variation of the visitor pattern.

like image 119
Sergey Kalinichenko Avatar answered Apr 30 '26 01:04

Sergey Kalinichenko


A nice workaround is using a matrix.

This will work well if you know that all the conditions will be evaluated anyway.

Make a multi-dimensional array that will map the true-false values to the handling functions.

Arrayswitch[var1][cond1][cond2][cond3][var2]();
like image 37
Yochai Timmer Avatar answered Apr 30 '26 00:04

Yochai Timmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!