Regarding errors, the Java Tutorial states:
The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
Also, the Programming With Assertions guide states:
Do not use assertions for argument checking in public methods.
So I think Exception are the right way to check for this kind of cases.
I recommend using a new UnsupportedOperationException("Operator " + name() + " is not supported.");
since it better describe the problem in my opinion (i.e. a developer added an enum value but forgot to implement the required case).
However I think that this sample case should use an AbstractEnum
design pattern instead of a switch:
PLUS {
double apply(double x, double y) {
return x + y;
}
},
MINUS {
double apply(double x, double y) {
return x - y;
}
},
TIMES {
double apply(double x, double y) {
return x * y;
}
},
DIVIDE {
double apply(double x, double y) {
return x / y;
}
};
abstract double apply(double x, double y);
It is less error prone since this code will not compile until every case implements apply
.