java - 什么时候应该使用 Apache Commons 的 Validate.isTrue,什么时候应该只使用 'assert' 关键字?

标签 java validation assert apache-commons

什么时候应该使用 Apache Commons 的 Validate.isTrue,什么时候应该只使用 'assert' 关键字?

最佳答案

Validate.isTrue 和 'assert' 的用途完全不同。

断言
Java 的断言语句通常用于记录(通过 断言)在什么情况下可以调用方法,以及 他们的来电者之后可以期望是真的。断言可以 可选地在运行时检查,导致 AssertionError 如果它们不成立则异常(exception)。

在契约设计方面,断言可以用来定义 前置条件和后置条件以及类不变量。如果在运行时 检测到这些不成立,这指向设计或实现 系统问题。

验证.isTrue
org.apache.commons.lang.Validate 是不同的。它提供了一个简单的集合 类 JUnit 方法的检查条件,并抛出 如果条件不成立,则为“IllegalArgumentException”。

通常在公共(public) API 应该容忍错误时使用 输入。在这种情况下,它的合约可以 promise 抛出一个 错误输入时出现 IllegalArgumentException。 Apache 验证报价 一个方便的简写来实现它。

由于抛出了 IllegalArgumentException,所以没有意义 使用 Apache 的验证来检查后置条件或不变量。 同样,使用“断言”进行用户输入验证是不正确的, 因为可以在运行时禁用断言检查。

同时使用
不过,同时使用两者是可能的,尽管 为了不同的目的。在这种情况下,契约(Contract)应明确 要求在某些类型上引发 IllegalArgumentException 输入。然后通过 Apache Validate 实现。 然后也简单地断言不变量和后置条件 尽可能附加先决条件(例如影响 对象的状态)。例如:

public int m(int n) {
  // the class invariant should hold upon entry;
  assert this.invariant() : "The invariant should hold.";

  // a precondition in terms of design-by-contract
  assert this.isInitialized() : "m can only be invoked after initialization.";

  // Implement a tolerant contract ensuring reasonable response upon n <= 0:
  // simply raise an illegal argument exception.
  Validate.isTrue(n > 0, "n should be positive");

  // the actual computation.
  int result = complexMathUnderTrickyCircumstances(n);

  // the postcondition.
  assert result > 0 : "m's result is always greater than 0.";
  assert this.processingDone() : "processingDone state entered after m.";
  assert this.invariant() : "Luckily the invariant still holds as well.";

  return result;
}

更多信息:

  • Bertrand Meyer,“按契约(Contract)应用设计”,IEEE 计算机,1992 年(pdf)
  • 约苏亚·布洛赫。 Effective Java,第 2 版,第 38 项。检查参数的有效性。 ( google books )

关于java - 什么时候应该使用 Apache Commons 的 Validate.isTrue,什么时候应该只使用 'assert' 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5049163/

相关文章:

java - Collections.sort - "should implement java.lang.Comparable"

java - 是否有任何可靠的建议来源支持或反对使用 Optional 作为对象转换机制

java - 正则表达式: Consecutive Repetitions with a Letter In Between

oracle - PL/SQL 检查日期是否有效

PHP sanitizer /验证整数数组

javascript - 在我的日期验证中合并前导零

unit-testing - 使用RhinoMocks,我如何断言调用了几种方法之一?

java - 将十六进制字符串转换为长17位java

捕获带有副作用的 assert()

java - Java中的断言机制