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.error开发者_StackOverflow中文版s:
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.
I argue for the exact opposite: In a validation layer you want to ensure that every validation error is handled. If you rely on return values, there might be a bug in the integration code (especially when you use the validators in a different environment).
Python exceptions will make that problem obvious.
精彩评论