Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement inside a switch statement?

Tags:

I have to evaluate many conditions. In my case, I have to do something like this:

switch(id) {     case 5:          // switch some other cases here     case 6:          // set some value     ...  } 

Is it good practice to have another switch in case 5? If not, what's better? Having if statements there?

like image 435
grady Avatar asked May 23 '11 12:05

grady


2 Answers

I'd call a function that was specific to case 5, then have the switch case in that function. For example :

switch(id) {     case 5:          FunctionFiveSpecific(id);     case 6:          // set some value     ...  } 

The function specific for case 5 :

private void FunctionFiveSpecific(id) {    // other switch in here } 
like image 54
Lloyd Powell Avatar answered Oct 13 '22 06:10

Lloyd Powell


The only thing that could be wrong with it is that it could hurt readability:

switch(id) {     case 5:     {         switch (somethingElse)         {             case 1:                 // blah...         }     }     case 6:          // set some value     ... } 

You could improve this by moving the nested section into a method:

switch(id) {     case 5:         Foo();         break;     case 6:          // set some value     ... } 
like image 39
Andrew Hare Avatar answered Oct 13 '22 07:10

Andrew Hare