简体   繁体   English

番石榴验证的目的是什么?

[英]What is the purpose of Guava's Verify?

What is the purpose of com.google.common.base.Verify when we have com.google.common.base.Preconditions ? 当我们有com.google.common.base.Preconditions时, com.google.common.base.Verify的目的是什么?

The Verify class looks nice but it has an @Beta annotation, should I use it? Verify类看起来不错,但它有一个@Beta注释,我应该使用它吗?

Torquestomp's answer is wrong (though it may have been correct for its time, I don't know). Torquestomp的答案是错误的(尽管它的时间可能是正确的,但我不知道)。 See gauva's wiki entry: Kinds of conditional failures . 请参阅gauva的wiki条目: 条件失败的种类

Precondition 前提

A precondition check ensures that the caller of a public method has obeyed the requirements of the method's specification. 前置条件检查确保公共方法的调用者遵守方法规范的要求。 For example, a sqrt function may accept only nonnegative arguments. 例如,sqrt函数可能只接受非负参数。

Verification 验证

A verification check is used when you lack high confidence that an API you consume will meet its (real or implied) specification. 如果您对自己使用的API缺乏高信度将满足其(实际或隐含)规范,则会使用验证检查。 It's easiest to understand this type of check as "like an assertion in almost every way, but must remain enabled in production." 最容易理解这种类型的检查“就像几乎所有方面的断言一样,但必须在生产中保持启用状态。”

Don't worry too much though. 不要过分担心。 From guava API docs: 来自guava API文档:

In some cases the differences [between Preconditions and Verify] can be subtle. 在某些情况下,[前提条件和验证]之间的差异可能很微妙。 When it's unclear which approach to use, don't worry too much about it; 当不清楚使用哪种方法时, 不要过于担心 ; just pick something that seems reasonable and it will be fine. 只需选择一些看似合理的东西就可以了。

The difference is semantic. 区别在于语义。 Verify is used to ensure that invariants don't change, that Code which has been engineered to do a certain thing is actually doing that thing. 验证用于确保不变量不会发生变化,已设计为执行某项操作的代码实际上正在执行该操作。 In spirit: 在精神上:

int x = divide(10, 5);
Verify.verify(x == 2, "X should be 2");

Preconditions, on the other hand, are expected to fail when bad input is passed to a certain portion of the program, usually either from the user to the code, or from client code to code within another library. 另一方面,当错误的输入传递到程序的某个部分时,前提条件会失败,通常是从用户到代码,或从客户端代码传递到另一个库中的代码。 In spirit: 在精神上:

public int divide(int x, int y) {
  Preconditions.checkArgument(y != 0, "Can't divide by 0!");
  return x / y;
}

As to whether you should use a @Beta class, that entirely depends on the scope and foreseeable lifetime of the application you are building, and, asked alone, would probably be flagged as a "Primarily Opinion-Based" question. 至于你是否应该使用@Beta类,这完全取决于你正在构建的应用程序的范围和可预见的生命周期,并且单独询问,可能会被标记为“主要基于意见”的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM