签入范围前提 [英] Check in range precondition

查看:88
本文介绍了签入范围前提的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢番石榴的前提条件,但我真正需要的是另一种方法-检查数字是否在范围内.像这样的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方法都会为其检查的内容抛出特定的异常类型:NullPointerExceptionIllegalArgumentExceptionIllegalStateExceptionIndexOutOfBoundsException.广义范围检查没有比IllegalArgumentException更具体的异常了.
  • checkArgumentcheckState可以满足您的所有需求.您可以只写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 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.

另外:

  • 您可能想要在这里有太多不同的组合. @rsp提及的互斥/包容边界,等等.
  • 这是限制,只允许int作为边界,因此您真的很想在那里允许任何Comparable.
  • 此时,您注意到您只是在检查值是否包含在
  • 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.

这篇关于签入范围前提的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆