sonar-delphi
sonar-delphi copied to clipboard
New rule: Case statements should be exhaustive
Prerequisites
- [X] This rule has not already been suggested.
- [X] This should be a new rule, not an improvement to an existing rule.
- [X] This rule would be generally useful, not specific to my code or setup.
Suggested rule title
Case statements should be exhaustive
Rule description
Enums are commonly used in case statements to conditionally perform code. This rule would pick up cases where the options within the case are not exhaustive, i.e. some values are missing and a default is not provided.
For example, the case below could be fixed by adding an meBaz or else option.
type
TMyEnum = (meFoo, meBar, meBaz);
procedure DoThing(EnumValue: TMyEnum);
begin
case EnumValue of // Noncompliant - missing meBaz
meFoo: WriteLn('Foo');
meBar: WriteLn('Bar');
end;
end;
Rationale
In cases where control flow is being alternated by enum values, a valid path should exist for all possible values. This is generally accepted as good practice.
In addition, any new values that are added to an enum should be handled in all existing alternations to prevent unexpected behaviour. Many programming languages enforce exhaustiveness of switch/case statements at compile time because of this - this rule helps enforce this for Delphi.
This rule is a great idea.
We probably won't put it in the default Sonar way profile, but exhaustive case statements are a very sensible thing to enforce across the board.