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.
-
6Why do you think the Chain of Responsibility design pattern is the best fit?Adam Zuckerman– Adam Zuckerman04/03/2014 05:15:42Commented Apr 3, 2014 at 5:15
2 Answers 2
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
-
1new url of Fluent Validation: github.com/JeremySkinner/FluentValidationBrij– Brij04/09/2019 09:03:23Commented Apr 9, 2019 at 9:03
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– Neil09/30/2014 07:48:01Commented Sep 30, 2014 at 7:48