Design Patterns – Design Pattern for Data Validation

design-patterns

What would be the best design pattern for this problem:

I have an Object A. Object A can either be registered or deleted from the database depending on the user request.

Data validation is performed before registration or deletion of the object. There are a set of rules to be checked before the object can be registered and another set of rules for deletion. Some of these rules are common for both operations.

So far, I think the Chain of Responsibility design pattern fits the most but I'm having trouble implementing it.

Best Answer

Normally I'll use a separate validator class to validate each use case. E.g. before adding product to database, I'll use AddProductValidator to validate business rule, before deleting product, I'll use DeleteProductValidator to validate, etc. Common business rule can be extracted to specification class (Specification pattern) and shared by validator classes

To structure validator class, I follow the approach here: http://lostechies.com/jimmybogard/2007/10/24/entity-validation-with-visitors-and-extension-methods/

If you use .NET, I think you might want to consider Fluent Validation (https://github.com/JeremySkinner/FluentValidation). I think it's quite cool and quite close to the article I mentioned above

Related Topic