Check in range precondition

六眼飞鱼酱① 提交于 2019-12-04 14:49:15

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.

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.

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