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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With