What is the best way to validate input? For argument's sake, if the input is invalid, the user would like a message explaining why.
Here is what I can come up with.
Validator
method: Pass input to the validator, which returnstrue
if the input is valid. Otherwise, the validator either returnsfalse
(or an error code) and lets the caller handle the invalid input. Or the validator takes the responsibility of taking action itself. Or the validator calls a callback method. Drawbacks: the steps taken to validate might be repeated when the actual method is called.Pass the input directly to the method, without validation. Let the method handle invalid messages itself. It can either send the error message to the user directly or use a callback method. After sending the message, the method must return or throw an exception to stop processing the invalid input. The calling class will continue to the next line of input. Drawbacks: this method now has a side effect of sending an error message.
What is the appropriate strategy here? Note that I do not believe throwing exceptions is appropriate because handling invalid input is a core function of the application, at least in my case.