I just struggled over this code:
int convert(ChangeType changeType) {
switch (changeType) {
case CREATE:
return 1;
case MODIFY:
return 2;
case DELETE:
return 3;
default:
throw new InternalError("changeType is null");
}
}
And the corresponding enum:
public enum ChangeType {
CREATE, MODIFY, DELETE;
}
I wondered: The default clause is obviously wrong, because it is meant to catch null, but null will call an NPE on line 2 of the listing.
But while experimenting, I found that removing the default case ends up in the compile error "missing return statement", but without adding more values to the enum this switch is "complete" and there is no such uncovered code path.
Q: So, is it really expected (as a user of this enum), that I add a default case which is actually a dead (and untestable) code path unless someone changes the enum?
Instead, I would even expect that code analyzers like Sonar warn if there is a complete switch and a default case.
PS: The code is only an example. I know there is Enum.ordinal()
which replaces most of the above code