Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a validate method throw an exception?

I've implemented a little validation library which is used like this:

domain_object.validate()

# handle validation errors in some way ...
if domain_object.errors:
    for error in domain_object.errors:
        print(error)

validate() performs the checks and populates a list called errors.

I know from other validation libraries that they throw exception when validation is performed unsuccessfully. Error messages would be passed as an exception property.

What approach is better? Is it advantageous to throw validation exceptions?

like image 806
deamon Avatar asked Jul 26 '11 09:07

deamon


1 Answers

No, I wouldn't think that a validation method should throw an exception.

That would create a bit of an anti-pattern, as the client code calling the method would reasonably expect an exception to be thrown, and would then need to catch the exception. Since it's generally recommended that exceptions not be used for flow control, why not just return a value indicating whether validation was successful or not. The client code could check the return value and proceed accordingly.

You essentially accomplish the same thing as you would by throwing an exception, but without the extra cost and poor semantics of actually throwing an exception.

Exceptions should be reserved for truly exceptional conditions, not normal operation of a program. Failing validation to me seems like it is a pretty normal condition, something to be expected during the day-to-day operation of an application. It would be easily handled by the calling code, and normal operation would continue. Generally, that's not the case with exceptions.

like image 176
Cody Gray Avatar answered Sep 24 '22 05:09

Cody Gray