Enum Switch Should Cover Every Constant
ID |
java.switch_on_enum_full_coverage |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:478, code-style, reliability |
Description
Reports a switch statement over an enum that leaves at least one of the enum’s constants unhandled and declares no default. Adding a constant to the enum then silently changes what the switch does.
Rationale
An enum switch that names only some of the constants compiles cleanly and skips its whole body for the rest. The danger is in the future: adding a constant to the enum produces incorrect behaviour at every switch site that does not handle it, with no compiler diagnostic anywhere.
enum Color { RED, GREEN, BLUE }
// Bad: BLUE is unhandled and there is no default
switch (color) {
case RED:
paint(RED);
break;
case GREEN:
paint(GREEN);
break;
}
Scope
This rule owns enum switches; java.missing_switch_default covers the rest. A switch is reported only when all of the following hold:
-
the selector’s type resolves to an enum declared in the analyzed project — an
int, aStringor an Android resource id is not an enum switch, however enum-like its labels read; -
at least one of the enum’s constants is not named by a case label;
-
the switch has no
default, which would otherwise absorb the unhandled constants.
The constants come from the project-wide software model, so an enum declared in another file is decided as readily as one in the same file. What the model does not hold, the rule does not answer for: a JDK or third-party enum is not indexed at all, and a selector whose type does not resolve gives nothing to look up. In both cases the switch is left unreported rather than guessed at.