I like guava preconditions, but what I really need from it is one more method - check that the number is in 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'm not alone and it's a pretty common case. But such method doesn't exist. Is there any reasons to not put such methods in com.google.common.base.Preconditions
?
There are quite a few reasons I'd say. Here are the main ones:
- There's no standard Java exception type for "value out of range". Note that each of the
Preconditions
methods throws a specific exception type for what it checks:NullPointerException
,IllegalArgumentException
,IllegalStateException
orIndexOutOfBoundsException
. A generalized range check would have no exception more specific thanIllegalArgumentException
to throw. checkArgument
andcheckState
do everything you need. You can just writecheckArgument(value >= min && value <= max, ...)
. It's simple and obvious what you're checking.
Additionally:
- There are too many different combinations you might want here. Exclusive/inclusive bounds as @rsp mentions, etc.
- It's limiting to only allow
int
s for the bounds, so you would really like to allow anyComparable
there. - At this point you notice you're just checking if the value is contained in a Range.
I think you can get very close by using checkArgument()
:
checkArgument(min < value && value < max, "%s must be in range [%s, %s]", value, min, max);
which, if you add the message strings to your own constant definitions, isn't much boilerplate and has all the flexibility you need.
来源:https://stackoverflow.com/questions/8217855/check-in-range-precondition