A class that manages a shared list of bookings has a class invariant relating its fields. Match each safeguard the designers use to the way it keeps the object from ever reaching a state that breaks the invariant.
An object being created from starting values that already break the rule
An outside reference to a mutable list changing internal data after it was stored or returned
A violation going unnoticed during testing until much later, far from the faulty method
Client code assigning new values to the state directly and skipping every check
A rejected request leaving some fields changed and others unchanged
Defensive copying
Check-then-commit update
Private fields
Constructor validation
Representation check
Unlock full course notes by signing up
Publishing a Valid Replacement State
A queue stores its fields together in an immutable state record, meaning the record cannot be modified after creation. Its current record satisfies the class invariant. An append method receives a text request. Parsing the text and constructing a proposed record can throw exceptions. Publishing a record uses one non-throwing reference assignment. In this sequential implementation, arrange the successful-operation steps so preparation failures leave the current record untouched and a notification callback can inspect only a validated state. If validation fails, the method rejects the proposal without publishing it.
Tracing State Through Rejected Calls
A ticketing system models one block of seats with the class below. Its invariant is that held and reserved are never negative and held + reserved <= capacity.
The object is created as SeatBlock(120, 70). The calls below are then made in order; each is wrapped so that a raised ValueError is caught and the program continues with the next call.
After call 8, give the final value of held, the final value of reserved, the number of free seats (capacity minus held minus reserved), and the number of calls that were rejected. Answer each as a whole number.
Finding Hidden Routes to Invalid State
A parcel batch stores a mutable list of nonnegative integer weights in grams and a cached total. Its class invariant requires the cached total to equal the sum of the list. Initially, the weights are 160 g and 90 g, and the total is 250 g. An addition method appends a weight before updating the total. The object remains usable after exceptions, and callbacks can call its public methods. Assume sequential execution. Which statements are true? Select all that apply.