Keeping Object State Consistent

Class Invariants describe the state an object promises to maintain throughout its usable life. They help you decide whether a constructor or method leaves behind an object that other code can safely use. The focus is the relationship among stored values, rather than whether one particular request is acceptable.

Expressing the state rule

A class invariant is a condition that holds for every externally observable valid state of an object. It can constrain one field, several fields together, or a stored value and the data it summarizes. An invariant need not describe one fixed value: fields can change while their required relationship stays true.


For a room-booking object, let cc be its capacity in seats and bb its booked-seat count. A suitable invariant is


I(c,b)=(c∈Z)∧(b∈Z)∧(c≥0)∧(0≤b≤c).I(c,b)=(c\in\mathbb{Z})\land(b\in\mathbb{Z})\land(c\geq 0)\land(0\leq b\leq c).


Here, II names the condition being checked. The rule excludes negative counts and bookings beyond capacity. It also permits an empty room, a full room, and a room with zero capacity.


Example: A room with capacity 18 seats and 11 booked seats can accept four additional bookings. The resulting count is 11+4=1511+4=15 seats, and 0≤15≤180\leq15\leq18 still holds. The booked count changed; the invariant did not.


Compare the persistent rule with requirements attached to a particular operation:


Kind of requirement

Booking example

What it concerns

Object-state rule

Booked seats remain between zero and capacity

Every observable valid state

Requirement for a call

The requested booking count is positive and fits

Whether this request is acceptable

Required effect

A successful booking increases the count by the requested amount

What this operation changes


A positive request alone does not establish the invariant. A request can be positive and still exceed the available seats.

Establishing and preserving the rule

A constructor establishes the invariant before making a successfully created object available to its caller. Checking only later methods cannot repair an invalid initial state automatically.


After construction, reason about each public method using the same pattern: assume the invariant holds at entry, identify the accepted requests, and show that every observable outcome preserves the rule. A method that merely reads state normally leaves it unchanged. A method that changes capacity must check its effect on bookings just as carefully as a method that adds bookings.



For a proposed booking of qq seats, calculate the proposed count b′=b+qb'=b+q. Accepting only appropriate integer requests with q>0q>0 and b′≤cb'\leq c preserves the booking bounds, assuming the entry state was valid.

Boundaries, failures, and access

A method may need several assignments to finish an update. In ordinary sequential code, the invariant can be temporarily false between those assignments if the intermediate state cannot be observed and execution reliably restores it before an observable exit.


Three boxes show consistent state at public entry, internal updates, and consistent state at public exit.


An observer includes a callback, not just the original caller. Calling external code halfway through an update can expose an inconsistent object even when the method eventually repairs it.


Failures matter too. If an exception leaves the object available for further use, its state must still satisfy the promised invariant. You can validate and prepare changes before mutation, or restore a valid state before propagating the failure. Preserving the invariant does not always require restoring the exact original state.



These principles assume sequential execution. Concurrent access requires additional coordination so other execution threads cannot observe incomplete updates.

What to remember

  • State the invariant as a precise condition on object state.
  • Constructors establish it; public operations preserve it.
  • Check failures and callbacks as well as successful returns.
  • Control every route by which stored state can change.

Example: Preserving a Locker Manager's State

A locker manager stores integer counts for capacity cc, occupied lockers oo, and held lockers hh. A held locker is reserved for a customer but is not yet occupied. Its class invariant is


c≥0,o≥0,h≥0,o+h≤c.c\geq0,\qquad o\geq0,\qquad h\geq0,\qquad o+h\leq c.


The manager starts with capacity 48 lockers, 19 occupied lockers, and 7 held lockers. Assume sequential execution. Ordinary integer field assignments in this example do not throw exceptions.


a) How many additional lockers can be held without violating the invariant?


First count the lockers already committed. Occupied and held lockers are separate commitments, so both reduce the available space. Their combined count is ________.


o+h=19+7=26 lockers,Available=48−26=22 lockers.\begin{aligned} o+h&=19+7=26\ \text{lockers},\\ \text{Available}&=48-26=22\ \text{lockers}. \end{aligned}


All existing counts are nonnegative, and the combined commitment is within capacity. Holding another 22 lockers would make the combined count exactly 48; holding another 23 would exceed capacity.


The largest additional hold is 22 lockers.


b) Starting from the original state, a customer requests a hold on 18 more lockers. Should the manager accept it, and what are the resulting held and available counts?


Prepare the proposed held count without changing the current state:


h′=7+18=25 lockers.h'=7+18=25\ \text{lockers}.


The proposed combined commitment is ________. Check that proposal against capacity and then calculate the remaining space:


o+h′=19+25=44 lockers,44≤48,Available′=48−44=4 lockers.\begin{aligned} o+h'&=19+25=44\ \text{lockers},\\ 44&\leq48,\\ \text{Available}'&=48-44=4\ \text{lockers}. \end{aligned}


The request is positive, the resulting counts are nonnegative, and the proposed commitment fits. The manager should accept the request, leaving 25 held lockers and 4 available lockers.


c) From the state after part b), six held lockers become occupied. The implementation increases the occupied count first, invokes a callback that can inspect the manager, and then decreases the held count. Is that callback placement safe, and what should the completed counts be?


The transfer moves existing commitments between categories; it does not create new commitments. Compute both intended results:


o′=19+6=25 lockers,h′=25−6=19 lockers.\begin{aligned} o'&=19+6=25\ \text{lockers},\\ h'&=25-6=19\ \text{lockers}. \end{aligned}


After only the first assignment, however, the held count is still 25. The intermediate combined count is ________.


25+25=50 lockers>48 lockers.25+25=50\ \text{lockers}>48\ \text{lockers}.


The callback could observe that invalid state. Restoring the invariant later does not make an earlier observation safe. Move the callback after both non-throwing assignments, with no intervening observer. Before beginning the update, also check that six held lockers are available to transfer.


Once both assignments are complete,


25+19=44 lockers≤48 lockers.25+19=44\ \text{lockers}\leq48\ \text{lockers}.


The original callback placement is unsafe. The completed valid state has 25 occupied lockers, 19 held lockers, and 4 available lockers.

A room-booking class stores its seat capacity and booked-seat count. Which statement describes a class invariant rather than a requirement for one particular operation?

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

A device pool stores integer counts for capacity, active devices, and reserved devices. Its class invariant requires all three counts to be nonnegative and active plus reserved not to exceed capacity. For each candidate state, enter the committed total as an exact integer and enter yes or no for whether the complete invariant holds.

StateCapacity (devices)Active (devices)Reserved (devices)Committed total (devices)Invariant holds
A24138
B24179
C24-25
D000

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 byte buffer has capacity 4096 bytes, contains 2750 used bytes, and reserves another 486 bytes. Its class invariant requires nonnegative integer counts and used plus reserved not to exceed capacity. An append operation increases only the used count. What is the largest number of bytes it can append while preserving the invariant? Answer in bytes, as a whole number.

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