Would you hire a contractor to build you a house without a contract? That's asking for a disaster.
When writing a program that is safe from bugs, easy to read, and ready for change, specifications help. Specifications describe how a program should behave. It allows you to remember what should go into a function, and what should return. It helps other contributors to develop different parts of the code without requiring full knowledge of the system.
Specifications consist of two major parts:
- The Precondition: this is the obligation on the caller of the method, or the client.
- The Postcondition: this is the obligation on the implementer of the method.
The relationship between them is simplified as: if the precondition is valid, then the method is obligated to adhere to the postcondition and return the appropriate action. If not, then the method is free to do anything... terminating (or not), throwing exceptions, returning arbitrary results, or doing nothing.
So in a marriage (like a pairing contract), if both parties honor their vows, then they should continue to stay married. If one side breaks their vow, then the other side has the right to choose to break up or still continue, or whatever (I'm not a marriage counselor).
The specifications of a method should talk about its parameters and its return values. Mentioning local variables or instance members is not necessary.
Specifications help us write good programs:
- Safe from bugs: specifications document the conditions and assumptions that the program relies on. Bugs come from mismatches at the interfaces.
- Easy to understand: a simple spec is easier to read and saves others the trouble of having read through the whole source code.
- Ready for change: specs establish a mutual relationship between different parts of the code. They are allowed to change so long as the conditions are met.