liveBook · Manning

Invariant

As explained in Object-Oriented Software Design in C++

A design principle stating that a class condition must remain true throughout the runtime of its objects.

A class invariant is a Boolean condition that must hold after construction and after every public operation changes an object’s state. It prevents objects from being left invalid, although mutation may violate the condition briefly. section 6.3.4

Apply the principle by:

  • Expressing a condition over the class’s member variables. section 6.3.4
  • Checking it before a constructor or state-changing member function returns. section 6.3.4
  • Using preconditions and postconditions alongside the invariant to define permitted calls and expected results. section 6.3

CircularBuffer

A circular buffer keeps head and tail within the range 0 through capacity minus 1: (0 <= head < capacity) and (0 <= tail < capacity). Incrementing each index with modulo capacity preserves this condition. Assertions check the invariant after construction and after add() or remove(); an invalid remove() call instead violates its precondition and aborts. section 6.3.1 section 6.3.4

(0 <= head < capacity) and (0 <= tail < capacity)

Inspect the compact invariant expression used for the circular buffer’s index bounds. section 6.3.4

How Object-Oriented Software Design in C++ covers it

How deep it goes
Traces invariant checking through constructors, mutators, assertions, temporary mutation, and modulo-based state preservation.
Examples
Demonstrates circular-buffer index bounds, modulo updates, assertions, and an invalid remove() call.
What it assumes
Assumes basic classes and member functions while teaching contract conditions through a concrete circular-buffer implementation.
What you can do after
Evaluate object-state rules and diagnose invalid transitions by writing invariant checks and assertions for critical C++ classes.
How it connects
Connects class invariants with programming by contract, preconditions, postconditions, constructors, and state-mutating member functions.

Also explained in

Compare how 12 books explain invariant →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.