Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Guava's Verify?

Tags:

java

guava

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?

like image 762
Morad Avatar asked Jun 15 '14 06:06

Morad


2 Answers

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.

like image 122
mcjohnalds45 Avatar answered Oct 09 '22 08:10

mcjohnalds45


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.

like image 23
torquestomp Avatar answered Oct 09 '22 09:10

torquestomp