Switch Default Not Last
ID |
java.switch_default_not_last |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style |
Description
Reports switch statements where the default case is not the last entry in the switch body.
Rationale
The default case is the catch-all: it handles every value not matched by explicit case labels. Placing it before other cases makes the switch harder to read and can mask bugs. Cases appearing after default may be silently unreachable if the default falls through, and developers scanning the switch expect the catch-all at the end.
// Bad -- default in the middle
switch (code) {
case 1: handleOne(); break;
default: handleOther(); break;
case 2: handleTwo(); break; // easy to miss
}
Remediation
Move the default case to the end of the switch body:
// Good -- default at the end
switch (code) {
case 1: handleOne(); break;
case 2: handleTwo(); break;
default: handleOther(); break;
}