Check in range precondition

你说的曾经没有我的故事 提交于 2020-01-13 05:22:06

问题


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?


回答1:


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.



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!