The specification of a class or interface is the collection of non-private items provided as services to the caller, along with instructions for their use, as stated in javadoc. It's a challenge to construct a specification which:
- is as simple as possible
- is as clear as possible
- has no ambiguity
- is completely accurate
- allows the reader to completely ignore implementation details (unless there is a bug)
- pours understanding into the mind of the reader as quickly as possible, with little chance for misunderstanding
The fundamental idea of Design By Contract is to treat the services offered by a class or interface as a contract between the class (or interface) and its caller. Here, the word "contract" is meant to convey a kind of formal, unambiguous agreement between two parties. C++ FAQs describes a contract as being made of two parts:
- requirements upon the caller made by the class
- promises made by the class to the caller
Some changes to a specification/contract will break the caller, and some won't. For determining if a change will break a caller, C++ FAQs uses the memorable phrase "require no more, promise no less": if the new specification does not require more from the caller than before, and if it does not promise to deliver less than before, then the new specification is compatible with the old, and will not break the caller.
Although Design By Contract is a formal part of some programming languages, such as Eiffel, it's not a formal part of Java. Nevertheless, Design By Contract is very useful for designing classes and interfaces. It can both guide the discovery of a more robust design, and allow more effective expression of that design in javadoc.
Requirements are simply any conditions on use, for example:
- conditions on argument values
- conditions on order of execution of methods
- condtions on execution in a multi-threaded environment
Promises are stated in javadoc. They can be enforced by assertions
at the end of a method.