简体   繁体   中英

Validation for java input parameters

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM