Is this a known/common pattern? (example in Java)
class BadInput extends Exception {
BadInput INSTANCE = new BadInput();
private BadInput() { }
}
Whenever INSTANCE
is thrown, it won't have a sensible stack trace but that's OK as it doesn't signify a coding error/resource issue/security issue/etc. (at a low level) but an input error (at a high level). Also, it won't explain why some input is bad. That's OK as well if no specifics are needed.
Here's a use case about (exact) integer division (a bit silly, but it becomes more practical if it deals with e.g. rationals or polynomials)
class ExactIntegerDivision extends BinaryOperator {
int compute(int arg1, int arg2) throws BadInput
{
if (arg2 == 0 || arg1 % arg2 != 0) throw BadInput.INSTANCE;
return arg1 / arg2;
}
}
If the exception is thrown, no cost is incurred in building a stack trace. All intermediate levels don't have the burden of having to check the validity of intermediate results since the exception simply propagates upwards (no checks as in if (!equalsErrorSentinel(subresult)) …
are needed, which avoids both performance-penalties as well as coding errors (such checks are bound to be forgotten sometimes).
It seems to be a great pattern (only to be used when the two OK's above are really OK of course). Why have I never come across it?
Aucun commentaire:
Enregistrer un commentaire