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 PP describe the precondition and QQ the postcondition. Use ss for the starting state, aa for the arguments, s′s' for the ending state, and rr for the result:


P(s,a)∧normal return⟹Q(s,a,s′,r).P(s,a)\land\text{normal return}\Longrightarrow Q(s,a,s',r).


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.


Three connected boxes show the caller obligation, operation execution, and implementation obligation on normal return.



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)1\leq k\leq\operatorname{old}(\text{stock}). On normal return, its postcondition requires:


stock=old⁡(stock)−k,r=k.\text{stock}=\operatorname{old}(\text{stock})-k, \qquad r=k.


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:


1≤k≤old⁡(stock),k is an integer.1\leq k\leq\operatorname{old}(\text{stock}), \qquad k\text{ is an integer}.


Its postcondition states the promised result on normal return:


stock=old⁡(stock)−k,reserved=old⁡(reserved)+k,r=k.\begin{aligned} \text{stock}&=\operatorname{old}(\text{stock})-k,\\ \text{reserved}&=\operatorname{old}(\text{reserved})+k,\\ r&=k. \end{aligned}


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≤91\leq9 is ________, and the statement 9≤419\leq41 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+1741+17; this provides a useful arithmetic check.


Subtract the request from available stock:


stock=41−9=32 units.\text{stock}=41-9=32\ \text{units}.


Add the same request to the reserved quantity:


reserved=17+9=26 units.\text{reserved}=17+9=26\ \text{units}.


The result must equal the requested quantity, so r=9r=9 units. The unchanged-note clause preserves the original text. The quantities also pass the check 32+26=5832+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−932=41-9. The returned value is correct because r=9r=9, and the note is unchanged.


However, the reserved quantity increased by only ________, calculated as 25−1725-17. The postcondition requires an increase of 9 units:


old⁡(reserved)+k=17+9=26 units.\operatorname{old}(\text{reserved})+k=17+9=26\ \text{units}.


The faulty ending quantities total ________, calculated as 32+2532+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.

An operation readAt(i) has the precondition 0≤i<length0\leq i<\text{length} and the postcondition that its result equals the element initially stored at index ii. The contract specifies no behaviour for invalid indices. A caller supplies i=8i=8 to a collection of length 8. Which conclusion follows from the contract?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.

Match each term
A.

Code that provides a routine and must deliver its promise for every legal call

B.

A condition the caller must make true before invoking a routine

C.

A condition the routine guarantees on return whenever it was entered legally

D.

A property every instance satisfies whenever it is observable from outside, between public calls

E.

Code that calls a routine and is entitled to its promised result

F.

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

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A printing account stores a whole-number balance of credits. The operation spend(x) has the precondition 1≤x≤old⁡(balance)1\leq x\leq\operatorname{old}(\text{balance}) and the postcondition balance=old⁡(balance)−x\text{balance}=\operatorname{old}(\text{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 holdsGuaranteed final balance (credits)
247
2424
240
2425

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice