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.
(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.
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]();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With