32

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.

asked Apr 3, 2014 at 3:50
1
  • 6
    Why do you think the Chain of Responsibility design pattern is the best fit? Commented Apr 3, 2014 at 5:15

2 Answers 2

21

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

answered Oct 30, 2014 at 7:48
1
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.

answered Apr 3, 2014 at 5:03
1
  • 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. Commented Sep 30, 2014 at 7:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.