Prohibiting passing certain values for method parameters

Omar Abdul'Azeez :

I have a method like this:

void method(int number){some code}

and i will call it like this:

method(-1)

is there a way in java to only allow passing positive integers to number parameter other than checking in the method body or making a checked exception?

chrylis -on strike- :

Declaring a checked exception doesn't make method parameters automatically validated somehow, it just means that the caller is obligated to check whether it was thrown, even if the code calls a literal method(1).

If your application is complex enough, you can use Bean Validation and put a constraint on the method parameter:

void method(@Min(1) int number) { }

This is only worthwhile if you're already using a system complex enough to provide support for it, such as Spring or CDI. Otherwise, just stick to checking in the method body and throwing IllegalArgumentException if the requirements fail. Guava's Preconditions utility can be helpful here.

(Additionally, your code will be much easier to read if you follow the universal Java code standards. Type names start with capitals, but member and parameters names start with lowercase.)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96887&siteId=1