Design by Contract
- Method callers (clients) and methods (servers) each have
contractual obligations to each other
- A client must only call a method if it knows that the precondition is true
- If it fails to do so, it has violated the contract
- A method must return with the postcondition being true
- Again, failure implies a contract violation
- Invariants have the following roles:
- Every constructor has every invariant as a postcondition
- Every method has every invariant as both precondition and postcondition
- Inheritance of contracts
- All invariants are inherited
- All preconditions and postconditions are inherited by any overriding
methods
- Inherited preconditions, if changed, must be weaker
- Inherited postconditions, if changed, must be stronger
- Formality of contracts
- Informal contracts are fine
- As development continues, they can become more formal
- Additional formality reduces ambiguity
- Specifying contracts
- Only use pure inspectors (i.e. no side effects)
- Write additional inspectors as necessary to help specification
Some examples
- Stack example:
- Sprite example: