switch over named constants carries a default clause
ID |
dart.correctness.no_default_cases |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Control Flow |
Language |
Dart |
Description
Reports a default clause in a switch whose case labels are named constants, such as enum values, rather than string or numeric literals.
Rationale
Without a default clause the analyzer checks that every value of the enumerated type is handled, and reports the switch as soon as a new value is added. A default clause removes that check: the switch keeps compiling, the new value silently takes the fallback branch, and the omission surfaces at runtime as behaviour that looks deliberate. What is meant as a safety net is therefore the thing that hides the change, and the more places switch on the type, the more of them go unnoticed.
The following code illustrates the pattern detected by this rule:
enum Shipment { pending, shipped, delivered }
class Tracker {
String label(Shipment state) {
// FLAGGED: switch over named constants carries a default clause
switch (state) {
case Shipment.pending:
return 'Pending';
case Shipment.shipped:
return 'Shipped';
default:
return 'Unknown';
}
}
}
Remediation
Remove the default clause and give every enum value its own case, so the analyzer reports the next value added to the type. When a real fallback is needed for a value from outside the program, keep the exhaustive cases and handle the unexpected value after the switch, or throw so the gap is loud rather than silent.