1

My use case requires me to implement multiple validators which implement the interface:

public interface Validator {
 boolean validate(Object o);
}

Based on the business group of the Object o, a different combination of validators need to be applied.

For each business group, I plan to maintain a list of Validators. This list will be maintained in an external configuration store. Ex:

BusinessGroupA {
 Validators = [v1,v2,v3,v4]
}

BusinessGroupB {
 Validators = [v3,v6]
}

What seems to be a good way to uniquely identify each validator from the list? Should v1,v2 be spring ids corresponding to their respective validators or do I need to explicitly create a unique identifier for each such validator and map that internally through a hashmap in my code?

Is there a better way to do this?

  • 2
    Why do you need to uniquely identify each validator from the list? Wouldn't you just apply each validator to the object in sequence? – gardenhead Jul 27 '16 at 18:29
5

Use an identifier that has an explicit name.
Validators with explicit names make your code so much more readable: instead of BusinessGroupA having validators 'v1', 'v2', 'v3' and 'v4' the CustomerOrderGroup is validated by the NoOutstandingPaymentsValidator, SufficientCreditValidator...

  • Thanks for the response! My only concern with that approach is possible duplication / name clash of two different validators. Is there some way to effectively eliminate that? – Rahul Jul 28 '16 at 3:47
  • Yeah, it's called a compiler. These are class names not simply strings. – candied_orange Jul 28 '16 at 4:28
  • Yeah, well if these 'identifiers' are class names this question would make no sense. It is clearly stated that v1 would be an id and I am making the case for these id's being in a human-understandable format. – JDT Jul 28 '16 at 7:52
  • I can't imagine any descriptive validator name clashing, but I'm not aware of the domain you are working in so I might be wrong. You might end up with some rather long names to guarantee 'uniqueness' but as long as those names are descriptive length should rarely be an issue. – JDT Jul 28 '16 at 7:54
  • Thanks for the responses. Are there any design related flaws with this approach (i.e. maintaining validators in the config) or is there any better,alternative way to achieve the same? – Rahul Aug 1 '16 at 19:17
0

Use a dependency injection (or IoC) framework.

What you are describing is a dependency injection framework which will load your dependencies for you via configuration.

Spring offers a DI framework.

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.