Java – check in scope precondition
I like the premise of guava, but what I really need is another way - check whether the number is in the range SMT like this
//probably there should be checkStateInRange also public static void checkArgumentInRange(double value,int min,int max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format("%s must be in range [%s,%s]",value,min,max)); } }
I believe I am not alone, this is a very common situation But this method does not exist Is there any reason not to be on COM google. common. base. Add this method to preconditions?
Solution
There are many reasons for what I said The following are the main contents:
>Out of range value has no standard Java exception type Note that each preconditions method throws a specific exception type for the content it checks: NullPointerException, illegalargumentexception, IllegalStateException, or indexoutofboundsexception There is no more specific exception than throwing illegalargumentexception in the broad range check. > Checkargument and checkstate can do everything you need You can write checkargument (value > = min & & value < = max,...) What you are checking is very simple and clear In addition:
>There are too many different combinations here@ The exclusive / inclusion limits mentioned in RSP only allow boundary injection, so you really want to allow any comparable. > At this point, you will notice that you just check whether the value is included in the range