22

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.

  • 6
    Why do you think the Chain of Responsibility design pattern is the best fit? – Adam Zuckerman Apr 3 '14 at 5:15
16

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

4

As described, I would probably implement an option type. That way I could return a "None" or a validated value (perhaps lazily) but that's an implementation detail and leads nicely to the idea of using a Decorator.

Decorator Pattern

Of course if the interface becomes ugly I would use a facade.

  • Decorator would work, but I usually think of Decorator pattern as something to be used when you want to transform the output into input for another class to use. In this case you'd simply be validating. I think chain of responsibility may work better imho. – Neil Sep 30 '14 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.