签入范围前提 [英] Check in range precondition
本文介绍了签入范围前提的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢番石榴的前提条件,但我真正需要的是另一种方法-检查数字是否在范围内.像这样的smt
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));
}
}
我相信我并不孤单,这是很常见的情况.但是这种方法不存在.是否有任何理由不将此类方法放在com.google.common.base.Preconditions
中?
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:
- 对于值超出范围",没有标准的Java异常类型.请注意,每个
Preconditions
方法都会为其检查的内容抛出特定的异常类型:NullPointerException
,IllegalArgumentException
,IllegalStateException
或IndexOutOfBoundsException
.广义范围检查没有比IllegalArgumentException
更具体的异常了. -
checkArgument
和checkState
可以满足您的所有需求.您可以只写checkArgument(value >= min && value <= max, ...)
.您正在检查的内容非常简单明了.
- 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.
另外:
- 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.
这篇关于签入范围前提的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文