In our Azure DevOps pipeline Sonar is expecting a switch expression for an enum to have a default case and returns the following error (with the full classpath).
Unable to parse source file : 'src/..../..../Service.java'
Parse error at line 22 column 18: A switch expression should have a default case
However adding a default case would turn a compile time error if a new item is added to the enum. To a runtime error when it hits the default case. Should SonarCloud be asking switch expressions on enums to have default cases?
Here’s a super basic example of this scenario.
class Scratch {
public static void main(String[] args) {
Scratch s = new Scratch();
System.out.println(s.switchExpression());
}
private Provider randomProvider() {
int randomNum = (int)(Math.random() * 10);
if (randomNum % 2 == 0) {
return Provider.ProviderFoo;
} else {
return Provider.ProviderBar;
}
}
private String switchExpression() {
return switch (randomProvider()) {
case ProviderFoo -> getFoo();
case ProviderBar -> getBar();
// Sonar wants a default case here
};
}
private String getFoo() {
return "foo";
}
private String getBar() {
return "bar";
}
}
// Adding a new item here would catch the error at compile time if there is no default case
public enum Provider {
ProviderFoo,
ProviderBar,
}