简体   繁体   中英

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 ?

The Verify class looks nice but it has an @Beta annotation, should I use it?

Torquestomp's answer is wrong (though it may have been correct for its time, I don't know). See gauva's wiki entry: Kinds of conditional failures .

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.

Verification

A verification check is used when you lack high confidence that an API you consume will meet its (real or implied) specification. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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