Design by Contract
Specify Operations with Design by Contract
Design by Contract makes an operation's obligations explicit at the boundary between its caller and implementation. Before you write the operation's algorithm, state which calls it accepts and what it promises afterward. This lets you reason about a call without examining every implementation detail. Here, the focus is on individual operations: their inputs, starting state, returned values, and permitted changes. Assume calls execute sequentially, without another operation changing the same state during execution.
Establish the entry obligation
A precondition is a condition the caller must establish immediately before invoking an operation. It can constrain an argument, the starting state, or their relationship. For example, requesting a positive quantity is insufficient if that quantity also has to be available in stock.
A postcondition is a condition the implementation promises on normal return, provided the precondition held when the call began. It can describe the result, the new state, and how those values relate to the old state.
Let P describe the precondition and Q the postcondition. Use s for the starting state, a for the arguments, s′ for the ending state, and r for the result:
The promise depends on the entry condition having held. This rule alone does not establish that the operation terminates or specify what happens if it throws an exception.
Write a precise promise
Use conditions that you can evaluate, rather than descriptions such as the stock is updated correctly. Identify which quantities refer to the starting state. The notation old(x) prevents an updated value from accidentally replacing the value the promise needs.
Example: A warehouse operation remove(k) accepts an integer number of units. Its precondition is 1≤k≤old(stock). On normal return, its postcondition requires:
If the initial stock is 52 units and the request is 14 units, the call is permitted. Its normal return must leave 38 units and return 14. Returning 14 while leaving 39 units violates the state requirement.
A promise may also state that particular data remain unchanged. If the operation must preserve a product description, include that requirement explicitly. A condition about stock alone does not establish what happens to the description.
Precision does not require specifying every internal step. Different algorithms can satisfy the same contract. Conversely, if a postcondition permits several results, the caller may rely only on their shared guarantees, unless another clause narrows the choice.
Interpret contract outcomes
Separate an unacceptable call from an implementation that breaks a promise. Check the precondition against the starting state before judging the ending state.
Entry condition | Observed outcome | Contract interpretation |
|---|---|---|
Holds | Normal return satisfies the postcondition | This execution meets the stated requirements |
Holds | Normal return violates the postcondition | The implementation breaks its promise |
Fails | Any observed outcome | The conditional promise does not establish an outcome |
Runtime checks can help detect violations, but writing a condition and checking it are separate decisions. A successful check on one execution also does not prove that every permitted execution will meet the contract.
For consecutive calls, use the first operation's postcondition to determine the state available to the next call. Then check the next precondition in that state. A valid first call does not automatically make the next call valid.
What to remember
- Establish the precondition before making the call.
- Read the postcondition using both starting and ending values.
- Apply the promise only under its stated conditions.
- Check each subsequent call against the state produced by the preceding call.
Example: Reserve Warehouse Stock
A warehouse stores whole-number quantities stock and reserved, measured in units. Here, stock means units still available for reservation. The operation reserve(k) has the following precondition, which the caller must establish:
Its postcondition states the promised result on normal return:
The product note must also remain unchanged. Initially, stock is 41 units, reserved is 17 units, and the product note is Handle upright. A customer requests 9 units. Assume the call returns normally and no other operation changes these values.
a) Does this request satisfy the precondition?
The request is an integer. Check the lower and upper bounds against the starting stock. The statement 1≤9 is ________, and the statement 9≤41 is ________. All required conditions hold.
Therefore, the request satisfies the precondition, and the implementation owes the stated postcondition on normal return.
b) Find the promised ending quantities, returned value, and product note.
Use the values immediately before this call, rather than updating a quantity and then treating it as an old value. The initial combined quantity is ________, found from 41+17; this provides a useful arithmetic check.
Subtract the request from available stock:
Add the same request to the reserved quantity:
The result must equal the requested quantity, so r=9 units. The unchanged-note clause preserves the original text. The quantities also pass the check 32+26=58 units.
The promised outcome is 32 available units, 26 reserved units, a returned value of 9 units, and the product note Handle upright.
c) A faulty implementation leaves 32 available units and 25 reserved units, returns 9 units, and preserves the note. Which requirement does it violate?
The entry condition held, so evaluate each promised clause. The stock clause is satisfied because 32=41−9. The returned value is correct because r=9, and the note is unchanged.
However, the reserved quantity increased by only ________, calculated as 25−17. The postcondition requires an increase of 9 units:
The faulty ending quantities total ________, calculated as 32+25, which also exposes the missing unit. The direct contract violation is the failed reserved-quantity equation.
Therefore, the implementation violates the reserved-quantity clause of the postcondition. A correct returned value does not compensate for an incorrect state change.
Match each Design by Contract term to the description of the role it plays when one piece of code calls a routine that another piece of code provides.
Code that provides a routine and must deliver its promise for every legal call
A condition the caller must make true before invoking a routine
A condition the routine guarantees on return whenever it was entered legally
A property every instance satisfies whenever it is observable from outside, between public calls
Code that calls a routine and is entitled to its promised result
Notation inside a guarantee that refers to a value as it stood on entry to the routine
Postcondition
Old expression
Class invariant
Client
Precondition
Supplier
A printing account stores a whole-number balance of credits. The operation spend(x) has the precondition 1≤x≤old(balance) and the postcondition balance=old(balance)−x on normal return. All requests below are integers, and each row is a separate call starting with 24 credits.
Complete the table. Enter yes or no for whether the precondition holds. Enter the exact guaranteed final balance in credits for a permitted call that returns normally. Enter not specified when the contract supplies no final-balance guarantee.
| Initial balance (credits) | Request (credits) | Precondition holds | Guaranteed final balance (credits) |
| 24 | 7 | ||
| 24 | 24 | ||
| 24 | 0 | ||
| 24 | 25 |