For my classes that have methods with similar input-checking logic (for example, a custom multi-dimensional array that has a lot of methods, all of which check if given coordinates are within the array limits), I create a separate private checker that throws runtime exceptions, and also a public checker, that just returns a boolean value indicating if a variable is acceptable for this class methods. Here’s example:
public class Foo {
public void doStuff(Variable v) {
checkVariableUnsafe(v);
... // do stuff
}
private void checkVariableUnsafe(Variable v) throws InvalidVariableException {...}
public boolean checkVariable(Variable v) {
try {
checkVariableUnsafe(v);
return true;
} catch (InvalidVariableException e) {
return false;
}
}
}
Is it OK to use it, or are there some downfalls that I fail to see? What’s the commonly used pattern in such situations?
It is often recommended to avoid using exceptions for normal program flow. Without debating that issue here, if you wanted to follow that advice, then you could put the logic that actually does the check in the public
checkVariablemethod, and have the privatecheckVariableUnsafemethod callcheckVariableand throw an exception if it returns false.I don’t think there is enough context in your question to comment definitively on the appropriateness of the API you have created, but I can see nothing intrinsically wrong with it.