Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO design patterns to use for validation

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?

like image 415
Peter Sankauskas Avatar asked Jul 14 '09 20:07

Peter Sankauskas


People also ask

How do you create a validation rule?

If you add a validation rule to an existing table, you might want to test the rule to see whether any existing data is not valid. Open the table that you want to test in Design View. On the Design tab, in the Tools group, click Test Validation Rules. Click Yes to close the alert message and start the test.

What is validation in OOP?

An important part of the OOP is too always keep your object in a valid state. Therefore, validation should be done after an input that could modify the object. It's always good to validate data comming from properties/set, parameters to functions and constructor.

How many OOP design patterns are there?

Although there are 23 design patterns listed in Design Patterns: Elements of Reusable Object-Oriented Software, of those there are 7 that are considered the most influential or important.

How are patterns used in object-oriented design?

Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development.


2 Answers

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)
like image 74
Wojciech Bederski Avatar answered Sep 22 '22 01:09

Wojciech Bederski


I think I am doing the same thing right now.
The pattern that applies here is the Filter pattern and the Filter Chain.

Each filter validates against one "way" (as you call them).
First for syntax, second for Db lookups etc (from your second bullet).

like image 32
Dimitrios Mistriotis Avatar answered Sep 22 '22 01:09

Dimitrios Mistriotis