0

I want to have a mechanism for method validation. What I am looking for is:

public void someMethod(@valid String emailAddress, @valid Integer ID) {
}

This is a general purpose class not necessarily java bean. The reason why I want this is that I want to decouple the validation logic away from this particular class.

Also I want to use DRY principle that means if various different methods are going to use the similar parameters so I neither want to duplicate the effort nor want to introduce inconsistencies handling the similar types of inputs.

Moreover, I want to make my code more readable as, otherwise, my method body will be sprinkled with if / then / else validation logic which will make it difficult to understand the actual logic and cause unnecessary distraction.

If my code were annotated with some logic, then someone such as spring has to call it - that part I think I understand. So I am not sure how I can implement this. Will aspect-oriented programming work?

3
  • You might want to lookup what the 'Hibernate Validator' can do for you. Commented Jun 24, 2016 at 0:41
  • You can create a proxy around your class that handles validation per parameter. Your annotation can have an element Class<? extends Predicate<?>> value() that will point to the validation class for that parameter, which will be instantiated and tested by your proxy. Commented Jun 24, 2016 at 1:38
  • I think this is exactly what AOP can do Commented Jun 24, 2016 at 1:50

1 Answer 1

2

If emailAddress and ID are used in several methods, I would create a class for each one, with validation logic in the respective constructors. That way you can guarantee every instance of those classes is valid. Then your method signature above becomes
public void someMethod(EmailAddress emailAddress, ID id) {}.

Basically, the root of your problem is using Strings and primitives with various semantic meaning. The simplest solution is to use custom, meaningful classes rather than Strings and primitives.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.