javaguavaassertion

Why doesn't Guava have postconditions? What can I use instead?


So, Guava has simple yet useful Preconditions to check method arguments. But I guess it would be reasonable to have a "Postconditions" class too. Or is it just because java provides assertions?

Since a class like this doesn't exist, what is the "best" (practice) alternative way to check postonditions before a mathod returns?


Solution

  • I would use the Java assert keyword within the method itself to encode the postcondition.

    Unit Test or Postcondition?

    Unit tests and postconditions serve different purposes.

    An assertion in a unit test provides a check on the result of a method for one input vector. It is an oracle specifying the expected outcome for one specific case.

    An assert in the method itself verifies that for any input the postcondition holds. It is an oracle specifying (properties of) the expected outcome for all possible cases. Such a postcondition-as-oracle combines well with automated testing techniques in which it is easy to generate inputs, but hard to generate the expected value for each input.

    Guava Postconditions?

    As to why Guava has a Precondition class, but no Postcondition class, here's my understanding.

    Guava Preconditions effectively provides a number of shorthands for common situations in which you'd want to throw a particular kind of exception (Illegal argument, null pointer, index out of bounds, illegal state) based on the method's inputs or the object's state.

    For postconditions there are fewer such common cases. Hence there is less need to provide a shorthand throwing specific kinds of exceptions. A failing postcondition is like a HTTP 500 "Internal Server Error" -- all we know something went wrong executing our method.

    (Note that Guava's notion of precondition is quite different from that of pure design-by-contract, in which there are no guarantees at all if a precondition is not met -- not even that a reasonable exception is thrown. Guava's Preconditions class provides useful capabilities to make a public API more defensive).