Switch statement inside a switch statement?

前端 未结 8 1795
傲寒
傲寒 2021-02-07 02:40

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:
          


        
相关标签:
8条回答
  • 2021-02-07 03:14

    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
        ...
    }
    
    0 讨论(0)
  • 2021-02-07 03:14

    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.

    0 讨论(0)
  • 2021-02-07 03:16

    Avoid !

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

    Strategy Pattern](![Strategy Pattern

    0 讨论(0)
  • 2021-02-07 03:24

    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

    0 讨论(0)
  • 2021-02-07 03:30

    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 讨论(0)
  • 2021-02-07 03:31

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

    0 讨论(0)
提交回复
热议问题