Is it a bad practice to write methods which return unthrown exceptions for the purpose of input validation? The Validate
method will return null if the input is valid, or return the exception that will be thrown should the input actually be submitted.
public Exception Validate(object input)
{
if (!SomeParametersMatch(input))
return new SomeException("Message...");
if (!SomeOtherParametersMatch(input))
return new SomeOtherException("Another message...");
// More cases here...
return null;
}
This way, you can use the same function for validating input, displaying responses to the user, and throwing exceptions in the code:
public void Submit(object input)
{
Exception ex = Validate(input);
if (ex != null) throw ex;
// Do whatever action here...
}
For example, if you're using the functions to mark spaces valid to click, you can call Validate
for each space, marking them valid if the return value isn't null. Then Submit
is only called once the user actually clicks on a space and the choice is finalized. This removes code duplication when you need to be able to ensure an input will be valid should you choose it.
I could make Validate
return a void and simply throw the exceptions, but since catching thrown exceptions is the most part of exception throwing, and Validate
will be run on many more invalid inputs than valid inputs, it seemed like a waste. If Validate
were only used when the user actually submitted data, I would have no problem using a try/catch block. But since it's being used to filter data presented to the user, throwing an exception the majority of the time, only to catch and discard it, seems ecessively wasteful.