24

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?

5
  • 1
    anything is fine as long as it works.
    – crypted
    May 23, 2011 at 13:02
  • @ThePower looking at Int3's profile and living in a world where the ideal solution cannot (or likely can never) be attained, I'm taking that comment with a pinch of salt. Sometimes whatever works is all that can be achieved at the time. Unfortunate and not always avoidable. May 23, 2011 at 13:05
  • 2
    Would any of your conditions disappear with usage of classes and polymorphism? May 23, 2011 at 13:09
  • 2
    You might also consider looking into a "table driven" approach. Often it is possible to turn a big nested switch statement into a dictionary or array lookup. May 23, 2011 at 15:06
  • @Eric can you show us some code.
    – crypted
    May 23, 2011 at 15:59

8 Answers 8

25

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
}
2
  • that post didn't seem to suggest that avoidance of non-nested switch is highly recommended. For nested switch, is there other particular reason why avoid switch? Except performance reason, which is not so relevant on today's machine.
    – liang
    May 1, 2013 at 9:29
  • 11
    It is highly recommended to avoid the use of switch statements if possible. dont spread fud. Something having a limitation is not a reason to avoid it for what it is capable of. foreach has limitation, why use it? Heck C# has limitations, why bother? switch is more readable, and insignificantly faster if it matters. But if you meant polymorphism, then I agree.
    – nawfal
    May 17, 2013 at 21:20
12

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
    ...
}
8

Avoid !

Try to refactor your code to eliminate switch cases. Switch statements for behaviours can be refactored into Strategy Pattern.

Strategy Pattern](![Strategy Pattern

2
  • 2
    +1 for separating polymorphic behaviour into strategies. unfortunately this is overwork for simple things where you cannot refactor your code because it comes from 'outside' :( May 23, 2011 at 13:16
  • 10
    can you provide a simple code example to your pattern? I am not sure I can understand how to translate from nested switches to this pattern..
    – Dennis
    May 9, 2014 at 21:15
7

Switch statements aren't bad practice. Nested switch statements might be messy to look at.

Perhaps think about embedding the nested switch statement in another method to improve clarity.

6

As soon as you start nesting your Cyclomatic complexity starts to rise. Depending on how complicated your nested switches are this can be fun to maintain. You might want to give some thought on moving the second nested switch to a function of its own. For example

switch (order.Status)
{
    case OrderStatus.New: 
        // Do something to a new order;
        break;

    ...

    case OrderStatus.ReadyToShip
        // Process Shipping Instructions
        ShipOrder(order);
        break;
}

and then if you had a switch based on the type of shipping paid for

void ShipOrder(Order order)
{
    switch (order.ShippingMethod)
    {
    }
}

By moving the second switch statement out of the first it's easier to maintain, and also can be tested in isolation

0
5

Better practice is to encapsulate the different behaviour polymophically inside different classes and try to avoid the switch statements if possible.

This is not always possible, and if you must use switch statements then I would not put another nested switch statement (or a collection of if statements) but would probably have a method call which would contain that logic.

If you post a bit more detail on what you are trying to do then we might be able to offer better suggestions.

1
  • Indeed, much suitable answer for this post. Imagine a code without if statements achievable by using one of the OOP concepts as mentioned here. May 23, 2011 at 13:10
2

Use Polymorphism if possible. This would make your code a lot cleaner.

1
  • 4
    Could you please be more specific and come up with code example?
    – shytikov
    Mar 12, 2015 at 10:09
1

I would call a function and pass in the aditional cases and in the function do a switch case on them. Makes cleaner code. Another method I often use is indeed nested if's

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.