Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any design pattern to avoid a nested switch case?

I have seen similar kind of threads, But, not sure how to exactly apply the solutions to my case. My problem is that i have a set of usecases lets say 'A','B','C',There are certain commands i need to execute when the input passed(2 usecases are the input) is any 2 of the listed usecases. for example:

switch(input1)
{
case A:
break;
case B:
break;
case C:
break;
}

inside the each case, i will have to check on input 2, so, the final code could look like

switch(input1)
{
case A:
{
switch(input2):
case B:
break;
case c:
break;
}
case B:
{
switch(input2):
case A:
break;
case c:
break;
}
....

}

I was thinking to use a map of (pair,command) and remove this switch cases, but is there any alternative better solution or design problem to solve this problem?

like image 378
user2063770 Avatar asked Dec 06 '25 17:12

user2063770


2 Answers

If performance is not that a big issue, then a map of function pointers could be one solution.

Assuming the label A, B , C ... are small integral values less than 255.

  • Setup the map first

    #define KEY(a,b)  ( (a<<8) | b )
    
    std::map<int, function_pointer_type>  dispatcher =
    {
        { KEY(A,B), ab_handler},
        { KEY(A,C), ac_handler},
        { KEY(B,C), bc_handler},
        //etc
    };
    
  • Use the map to invoke appropriate handler for each set of input:

     dispatcher[KEY(input1,input2)] (/* args */);
    

Note that you have to setup the dispatcher with each possible pair of inputs. Also, if the pair KEY(A,B) and KEY(B,A) are same case, then you can write a function called invoke to handle this case in order to provide uniform usage for the rest of the code.

 void invoke(int input1, int input2, /* args */)
 {
     if (dispatcher.find(KEY(input1, input2)) != dispatcher.end() )
           dispatcher[KEY(input1,input2)] (/* args */);
     else
           dispatcher[KEY(input2,input1)] (/* args */);
 }

then use it as:

 invoke(input1, input2, /* args */);
 invoke(input2, input1, /* args */);  //still okay!

Hope that helps.

like image 151
Nawaz Avatar answered Dec 08 '25 10:12

Nawaz


In your case, how about break the two switches into two functions

bool processInput2(char input2)
{
  switch(input2)
  {
   case 'A':
   {  
      // blah
   }
    break;
}

bool processInput1(char input1)
{
  switch(input1)
  {
   case 'A':
      processInput2(input2);
      break;
}
like image 32
billz Avatar answered Dec 08 '25 12:12

billz



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!