OO design patterns to use for validation

design-patterns, oop

Solution

One size does not fit all! Make it simple!

Provide validators with common methods/interface to output data, categorize warnings, filter/process warnings raised more than once. Do not create any sophisticated way of validation itself, at least not before writing a few real life validators.

Move out of the way and let the validators do what they are supposed to do:

for validator in all_validators:
    validator.validate(model)

Problem

I am in the process of writing some validation code based on these assumptions: - Validation code must be in an external class - i.e. no data class contains it's own validation - The same object can be validated in different ways - e.g. validate syntax only; validate against DB look-ups; validate against duplicates; etc - Validation output can be different depending on what needs it - e.g. output a single error message; output a list of all validation errors; similar but in JSON format and including error codes; etc What combination of OO design patterns are best to solve this? A factory might be a good way to get a specific validator, but are their better approaches?

Original source