How do I insert a precondition in a java class method or constructor?

Jay Rohrssen picture Jay Rohrssen · Nov 18, 2012 · Viewed 13.5k times · Source

This is for a java class I'm taking. The book mentions preconditions and postconditions but doesn't give any examples how to code them. It goes on to talk about asserts, I have that down, but the assignment I'm doing specifically states to insert preconditions and test the preconditions with asserts.

Any help would be great.

Answer

paulsm4 picture paulsm4 · Nov 18, 2012

Languages like Eiffel support "preconditions" and "postconditions" as a basic part of the language.

One can make a compelling argument that the whole purpose of an "object constructor" is precisely to establish "the class invariant".

But with Java (as with just about every other post-C++ object oriented language), you pretty much have to fake it.

Here's an excellent tech note on leveraging Java "assert":