I have a data model which contains an array of Product objects. Before reporting from this model I am required to run a set of rules which check the integrity of each Product object in the model. One way I can think of doing this is to have a Rule interface e.g.
public interface CheckRule {
boolean runRule(Product p);
}
For each rule I can then have a separate Rule class which implements the CheckRule interface. I can then have a double loop to run all the rules e.g.:
for (Product p : Products) {
for (Rule r : Rules) {
if (! r.runRule(p) {
// report on the broken rule
}
}
}
If I have hundreds of rules however I end up with hundreds of Rule classes, which seems a messy way to do it. An alternative is to have a single RuleManager class, which has a separate method for each rule e.g.
public class RuleManager {
boolean runRule1(Product p) { // rule 1 logic}
boolean runRule2(Product p) { // rule 2 logic}
boolean runRule3(Product p) { // rule 3 logic}
etc...
}
This reduces the number of classes, but means that I end up with a single class with hundreds of methods. Both methods feel wrong to me, and I was wondering if there is a Design Pattern which covers this scenario which I could use instead?
I think you’ll find that you can often parameterize rules, so that you won’t need anywhere near one class per rule. This is especially true if you’re willing to consider using reflection.
JSR303, aka Java Validation API, is good for simple field validation, but rapidly runs out of steam when you need to do more complex stuff.
Drools is not relevant, if I understand the use case – way too heavy.
Think carefully about how to handle validation errors. You want to be able to report multiple errors – don’t bail out on the first one, your users will hate you. So you probably want to have some kind of error collector object that the validators put the errors in, that is then returned by the validator framework.