I see some reasons to include in the switch statement.
1st: not instead of a break, but as the default case body. Consider the following example when the switch is listed:
pubic enum E { A, B }
The switch from the time it was first written looks like this:
E e = ...; switch (e) { case A: ... break; case B: ... break; default: throw new IllegalStateException("Unknown enumeration value " + e); }
A cast is a reserve for future extensions for listing E
2nd: Sometimes I have small getter functions, for example, in the Swing table model. There I use return instead of break;
public String getColumnName(int col) { switch (col) { case 0: return "Column 0"; case 1: return "Column 1"; ...
This is for brevity or compactness. It can be said that these returns break the flow of control. It's true. However, I think that for reasons of compactness this may be allowed here.
If you accept return instead of break , then you can also accept throw here.
Object[] x = ...; // get some array which is not null from a function which // only returns arrays, eg OSGI services switch (x.length) { case 0: throw new IllegalArgumentException("No service defined"); case 1: return x[0]; // return the only available service default: ... // evaluate all services and return the best matching one return x[...]; }
source share