Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prohibiting passing certain values for method parameters

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?

like image 816
Omar Abdul'Azeez Avatar asked Apr 30 '26 16:04

Omar Abdul'Azeez


1 Answers

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.)

like image 83
chrylis -cautiouslyoptimistic- Avatar answered May 02 '26 06:05

chrylis -cautiouslyoptimistic-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!