liveBook · Manning

Invariant failure

As explained in Unit Testing Principles, Practices, and Patterns

A condition in which software state no longer satisfies a rule that must remain true for the domain or component.

An invariant failure occurs when software state no longer satisfies a rule that must remain true. It often arises when a client must coordinate multiple operations that belong together. section 3.1

Encapsulation prevents invariant failures by eliminating invalid courses of action. Keeping related state changes behind one public operation also limits the risk of corrupted database state and inconsistent business outcomes. section 3.1

Purchasing inventory

A successful purchase must acquire the product and reduce store inventory together. If the client calls Customer.Purchase and separately calls Store.RemoveInventory, omitting the second call leaves the customer with an item while inventory remains overstated. Customer.Purchase should perform both changes, allowing the test's act section to contain one operation. section 3.1 section 3.7

Recognize and prevent invariant failures by:

  • Treat multiple client actions that must always occur together as a sign of an exposed or fragile API. section 3.7
  • Move coordinated state changes into a single public method that owns the business rule. section 3.1
  • Use unit tests to assert the combined observable outcomes rather than relying on client code to preserve consistency. section 3.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Explains causes, database consequences, and API remedies, but stops short of formal invariant specifications or verification techniques.
Examples
Uses a purchase that acquires a product and reduces store inventory as one business operation.
What it assumes
Assumes familiarity with clients, public methods, business logic, and the arrange-act-assert structure of unit tests.
What you can do after
Diagnose/debug with it by spotting multi-step client protocols and consolidating them behind invariant-preserving operations.
How it connects
Connects encapsulation, API design, unit testing, client coupling, and database corruption.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.