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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With