Misleading Switch Label
ID |
java.switch_bad_case |
Severity |
critical |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports an ordinary Java label (name:) placed directly in the statement list of a classic
switch case, rather than inside a nested loop or block further down. Labels are legal on any
statement, so the code compiles and runs as written, but a bare label sitting among case
clauses reads exactly like a case that lost its keyword.
Rationale
case, default and a plain label all end in a colon, and a plain label is free-floating text
that silently attaches itself to whichever statement follows — there is no compiler warning to
flag the missing case keyword. A maintainer skimming the switch has to stop and work out
whether the label was meant to introduce a branch or is simply naming a nested loop for
break/continue.
switch (status) {
case OPEN:
break;
PENDING: // FLAW -- looks like a missing "case", but is just a label
break;
case CLOSED:
break;
}
A label further inside the case, for instance on a loop nested in an if, is an ordinary
loop-control label unrelated to the switch and is not reported.
Remediation
If a branch was intended, add the missing case keyword. If the label is only there to break out
of a nested construct, move that construct (and its label) into a dedicated method, or push it
deeper so it no longer sits directly among the case labels.
switch (status) {
case OPEN:
break;
case PENDING: // Good -- explicit case keyword
break;
case CLOSED:
break;
}