Question

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?

Was it helpful?

Solution

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 or IndexOutOfBoundsException. A generalized range check would have no exception more specific than IllegalArgumentException to throw.
  • checkArgument and checkState do everything you need. You can just write checkArgument(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 ints for the bounds, so you would really like to allow any Comparable there.
  • At this point you notice you're just checking if the value is contained in a Range.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top