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
