We have a set of about two dozen classes that inherit from a base class which has an abstract Validate method. Of course each class has different validation needs but the rules are needed in different combinations between all of them so, as you can imagine, this resulted in a lot of code duplication, as an example:
Class A needs rules 1, 3, 6, and 9
Class B needs rules 3, 4, and 8
Class C needs rules 1, 8, and 9
….
you get the picture.
So I was thinking of doing a simple refactoring and create a Validation Decorator in which each rule would be encapsulated in a class and a factory that would create the adhoc validation combination for each class.
Then I started thinking that each rule is so simple that instead of creating all the plumbing for the decorator I could probably just have Action delegates stored in the factory which would populate a List(Action(T)) so that each class would just iterate through that list executing each delegate.
The problem is that the number and/or types of parameters vary between each rule, as an example:
Rule 1 needs a nullable DateTime, a DateTime, and an enum.
Rule 2 needs a nullable DateTime, and a DateTime.
Rule 3 needs a string …..
Is this something that can be accomplished or have I not choice but to code the Decorator?
Thanks for your thoughts and ideas.
UPDATE:
Some rule examples:
if(EndTime.HasValue && StartTime > EndTime)
Throw new Exception (...);
if(Status == StatusEnum.Pass && !EndTime.HasValue)
Throw new Exception (...);
if(string.IsNullOrEmpty(ProcessName))
Throw new Exception (...);
if(string.IsNullOrEmpty(ProductName))
Throw new Exception (...);
if(string.IsNullOrEmpty(CustomerName))
Throw new Exception (...);
All the involved classes have the properties DateTime? EndTime, DateTime StartTime, StatusEnum Status, and string ProcessName.
Why not make an interface called something like
IValidationParameterThen have each validation rule have an implementation of IValidationParameter. For exampleThen make your list
List<Action<IValidationParameter>>