No Nested Switch
ID |
csharp.no_nested_switch |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
CSharp |
Tags |
control-flow, reliability, switch |
Description
Reports a switch statement written inside another switch. The inner switch is reported once.
Rationale
A nested switch forces the reader to track two selector values and two sets of labels at the
same time, and the inner break statements read as though they left the outer switch. The number
of paths through the method is the product of the two label counts, so cases are easy to miss and
hard to cover with tests.
public string Route(int kind, int code)
{
switch (kind)
{
case 1:
switch (code) // FLAW — inner switch
{
case 10:
return "one-ten";
default:
return "one";
}
default:
return "other";
}
}
public string RouteFlat(int kind, int code)
{
switch (kind) // OK — the inner decision moved to its own method
{
case 1:
return RouteKindOne(code);
default:
return "other";
}
}
Remediation
Extract the inner switch into its own method named after the decision it makes, so each switch
has a single selector and a single set of labels. When both selectors belong together, consider a
switch on a tuple pattern ((kind, code) switch { … }) or a lookup table keyed by the pair.