签入范围前提条件
我喜欢番石榴前提条件,但我真正需要的是另一种方法 - 检查数字是否在范围内。 我相信
//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 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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说的原因有很多。主要如下:
Preconditions
方法都会针对其检查的内容引发特定的异常类型:NullPointerException
、IllegalArgumentException
、IllegalStateException
或IndexOutOfBoundsException
。广义范围检查不会抛出比IllegalArgumentException
更具体的异常。checkArgument
和checkState
可以完成您需要的一切。您只需编写checkArgument(value >= min && value <= max, ...)
即可。您要检查的内容简单明了。另外:
int
为边界,因此您确实希望允许任何Comparable
存在。There are quite a few reasons I'd say. Here are the main ones:
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:
int
s for the bounds, so you would really like to allow anyComparable
there.我认为您可以通过使用
checkArgument()
来非常接近:如果您将消息字符串添加到您自己的常量定义中,则不会有太多样板文件,并且具有您需要的所有灵活性。
I think you can get very close by using
checkArgument()
:which, if you add the message strings to your own constant definitions, isn't much boilerplate and has all the flexibility you need.