A base class CruiseControl defines setSpeed(s), where sss is an integer target speed in km/h and vvv is the speed the vehicle settles at after the call. Four subclasses override the routine with the contracts below. Client code is written against the base contract and may receive any of the subclasses at run time.
Class
Precondition
Postcondition
CruiseControl (base)
0≤s≤1200 \le s \le 1200≤s≤120
∣v−s∣≤2\lvert v - s \rvert \le 2∣v−s∣≤2
FastCruise
0≤s≤1500 \le s \le 1500≤s≤150
∣v−s∣≤1\lvert v - s \rvert \le 1∣v−s∣≤1
CityCruise
0≤s≤1000 \le s \le 1000≤s≤100
EcoCruise
∣v−s∣≤4\lvert v - s \rvert \le 4∣v−s∣≤4
TruckCruise
10≤s≤13010 \le s \le 13010≤s≤130
For each subclass, enter how many integer speeds that are legal under the base precondition its own precondition rejects. Then answer yes or no: does its precondition accept every base-legal input, does its postcondition guarantee at least the base promise, and can it safely substitute for the base class?
Unlock full course notes by signing up
Carry the state into the next call
A warehouse operation transfer(k) moves whole units from a source bin to a destination bin. Its precondition is 1≤k≤old(source)1\leq k\leq\operatorname{old}(\text{source})1≤k≤old(source). Its postcondition on normal return is:
Initially, the source contains 72 units and the destination contains 19 units. The warehouse calls transfer(16) and then transfer(25). Both calls return normally, and no other operation changes either bin.
A promise that permits several results
An operation findMatch(values, target) uses zero-based indices. Its precondition requires a nonempty integer array containing the target. Its postcondition guarantees that the array is unchanged and the returned integer rrr satisfies:
The input array is [4, 9, 4, 7, 4] and the target is 4. Assume the call returns normally. Which statements are guaranteed by the contract? Select every guaranteed statement.
Trace a monitored call
A language runtime monitors contracts while a client calls one public routine on an object. The monitor follows the usual rule that old expressions are evaluated only for a legal call, so that evaluating them can rely on the precondition. Put the events of this single call in the order they happen, from the client preparing the call to the client using the result.
Budget for a dependent fee call
An account initially contains 137 whole credits. The operation debit(k) accepts an integer amount. Its precondition is 1≤k≤old(balance)1\leq k\leq\operatorname{old}(\text{balance})1≤k≤old(balance), and its postcondition on normal return is balance=old(balance)−k\text{balance}=\operatorname{old}(\text{balance})-kbalance=old(balance)−k.
A client first calls debit(n), then calls debit(fee), where