I have a Java code with the following pattern:
enum Foo
{
ORANGE, APPLE, BANANA
}
Foo bar()
{
switch(calcValue())
{
case "orange": return ORANGE;
case "apple": return APPLE;
case "banana": return BANANA;
}
}
The design of calcValue method ensures it never returns anything else than the three strings that the switch statement checks. If it would not be able to return either of the three strings, it throws an exception. This implies that the missing default keyword may be unnecessary and the default switch behavior is never triggered, hence default is omitted. However, Java naturally (and rightfully so, in general) complains that bar must (always) return a value. I was thinking to throw an exception as default, but as mentioned calcValue throws one already. I am primarily after a simple and efficient (involving least runtime checks and code) design to solve this little problem – I don’t want to throw two exceptions, and calcValue is not under my control, so I cannot do anything with it.
I hope I have explained myself well here, if not, I will do my best to try to clarify. In essence, this is about designing methods with value where switch defaults are known to not apply. That may also apply to if-then-else-if-then-else-...-then-else statement patterns.
You wrote
However, this contract is not expressed by the signature of
calcValue; it just returns a string and the type checker of Java has no way to know that only some strings are possible. I’d consider this a flaw in the API of thecalcValuefunction.The bottom line is that Java is correct – you do lack a
defaultcase, since your assumption about the inner workings ofcalcValueis not enforced by the type system, so it may change at any point without the compiler noticing.