Switch statement inside a switch statement?

前端 未结 8 1799
傲寒
傲寒 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: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

提交回复
热议问题