25-Comp-B11 Advanced Software Design · December 2018
Question 10 of 28: Precondition, Postcondition, and the Importance of a Class Invariant
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer) · Last updated
Notes on this paper
Reference texts: Sommerville, Software Engineering (10th ed., Pearson) — software processes, requirements engineering, design principles, dependability; Pressman, Software Engineering: A Practitioner's Approach (9th ed.) — supplementary process and quality coverage; Gamma, Helm, Johnson & Vlissides (GoF), Design Patterns: Elements of Reusable Object-Oriented Software — creational/structural/behavioural pattern catalogue and the "program to an interface, not an implementation" / "favor object composition over class inheritance" principles; Sebesta, Concepts of Programming Languages (12th ed.) — polymorphism, dynamic binding, inheritance and language-level object semantics; Bertrand Meyer, Object-Oriented Software Construction — design by contract, preconditions/postconditions/invariants; Barbara Liskov's 1987 substitutability paper for Question 11; Karl Wiegers, Software Requirements (3rd ed.) — the functional/quality/process/implementation/business requirements taxonomy of Question 2; Kruchten, The Rational Unified Process: An Introduction, for Question 1; Myers, The Art of Software Testing, for Questions 6 and 28.
PART I — General Principles
Question 10: Precondition, Postcondition, and the Importance of a Class Invariant (Part II)
Precondition. A condition that must be TRUE before an operation is invoked, for the operation's guarantee to apply. It is an obligation on the CALLER — e.g., for withdraw(amount) on a bank account: amount > 0 AND amount ≤ balance.
Postcondition. A condition GUARANTEED to be true immediately after an operation completes, PROVIDED its precondition held on entry. It is a guarantee of the SUPPLIER — e.g., for the same withdraw(amount): balance_new = balance_old − amount.
Class invariant. A condition on an object's internal state that must hold TRUE whenever the object is in a stable, externally-observable state — immediately before and immediately after every public operation. For a bank account: balance ≥ 0, always.
Why the class invariant is important. It is the ONE contract clause that is not attached to any single method but instead defines what it MEANS for an instance of the class to be valid at all — every public method's own contract implicitly includes "preserve the invariant" as part of its postcondition, so the invariant is what lets a client reason about an object's state without re-reading every method's individual contract. It also gives a class author a single, explicit correctness target during implementation (every method body must restore the invariant before returning, even if it is temporarily broken mid-method), and it is the exact mechanism Question 12 uses to determine whether a subclass's added constraints are safe under inheritance.