25-Comp-B11 Advanced Software Design · December 2014
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer)
Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.
Definition. Design by Contract (DbC, Bertrand Meyer, originating in the Eiffel language) formalizes a class operation's obligations as an explicit CONTRACT between a supplier (the class) and its clients (callers), stated as a precondition (an obligation on the CALLER, which must hold before the call for the operation's guarantee to apply), a postcondition (an obligation on the SUPPLIER, guaranteed to hold after the call returns, provided the precondition held), and a class invariant (a condition on the object's state that must hold before and after every public operation).
Example. A Stack.pop() operation: precondition — !isEmpty(); postcondition — the stack's size decreases by exactly 1 and the returned value is the element that was previously on top; invariant — size ≥ 0 at all times. If a caller violates the precondition (calls pop() on an empty stack), the fault is unambiguously the CALLER'S; if the postcondition or invariant fails despite a satisfied precondition, the fault is unambiguously the SUPPLIER'S implementation.
Benefits. Contracts document each operation's real behaviour precisely and unambiguously (far more precisely than prose comments), and in languages with runtime assertion support they can be MACHINE-CHECKED. They sharply localize fault assignment when something goes wrong (caller vs. supplier), which speeds debugging. They also justify omitting redundant defensive checks inside the supplier — if the precondition already guarantees a non-empty stack, pop() need not re-check emptiness defensively, since a violated precondition is the caller's bug by contract, not a case the supplier must recover from gracefully.
Challenges. Writing and maintaining contracts alongside the code is extra effort, and runtime assertion checking has a real performance cost, often leading teams to strip it from production builds — removing exactly the safety net most useful for catching real violations. Many mainstream languages (historically Java, C++) lack first-class contract syntax, requiring library or annotation workarounds (assert, JML) rather than a language-enforced mechanism. Stating precise, correct contracts for complex, stateful, or concurrent operations (e.g., invariants spanning multiple collaborating objects) can become nearly as hard as writing the implementation itself, and a wrong contract only formalizes a wrong assumption rather than catching it — DbC complements testing, it does not replace it.