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:
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
...
}
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.
Avoid !
Try to refactor your code to eliminate switch cases. Switch statements for behaviours can be refactored into Strategy Pattern.
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
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
Use Polymorphism if possible. This would make your code a lot cleaner.