liveBook · Manning

Invariant

As explained in Unit Testing Principles, Practices, and Patterns

An invariant is a condition that must remain true for a software object or component.

An invariant is a condition that must remain true for a software object or component. Encapsulation protects that condition by preventing clients from bypassing the code that maintains it. section 5.5

A well-designed API exposes observable behavior while hiding implementation details. Publishing an operation used only to preserve an invariant leaks internal mechanics into client code. section 5.2 section 5.5

Use these rules when designing an invariant-preserving object:

  • Expose operations or state that help clients achieve their goals. section 5.5
  • Keep invariant-maintaining operations private when clients do not need to call them directly. section 5.2
  • Make client code express its goal directly instead of coordinating internal steps. section 5.2

Normalize a user name without leaking the invariant

User requires names to be trimmed and limited to 50 characters. A fragile API exposes NormalizeName, forcing UserController to call it before assigning Name. A simpler API makes NormalizeName private and invokes it inside the Name setter, leaving the client with only user.Name = newName.

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Works through definition, API consequences, and a User refactoring from leaked normalization to private enforcement.
Examples
Uses a User name-length rule, NormalizeName, the UserController rename flow, and a private setter-based refactoring.
What you can do after
Apply encapsulation by moving invariant-preserving work behind an API while exposing only client-relevant behavior.
How it connects
Connects invariants with encapsulation, observable behavior, implementation details, public APIs, and hexagonal architecture.

Also explained in

Compare how 12 books explain invariant →

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.