Invariant
An invariant is a condition or property that must remain true across the specified valid states, operations, or transformations of a system or computation.
100 C++ Mistakes and How to Avoid Them
A class invariant is a condition on an object's state that must hold whenever the object is usable, including after construction and public operations.
- How it is used
- Uses invariants to guide correct class design and identify state corruption in existing C++ code.
- How deep it goes
- Explains construction and mutation checks, then examines inheritance, copying, resource ownership, and exception recovery.
- Examples
- Uses a Person with an uninitialized age and a Rectangle–Square inheritance conflict to expose invalid states.
- What you can do after
- Diagnose/debug invariant violations and apply constructor validation and controlled mutation to protect object state.
Read how 100 C++ Mistakes and How to Avoid Them explains invariant →
Data-Oriented Programming in Java
An invariant is a condition that must remain true across the valid states of a data structure or computation.
- How it is used
- Uses domain meaning to turn correctness requirements into constraints at construction, type, refactoring, testing, and integration boundaries.
- How deep it goes
- Develops runtime constructor validation, compile-time type modeling, formal statements, property tests, and database-verified state transitions.
- Examples
- Uses Rational denominators, oil-curing measurements, late-fee lifecycles, shopping carts, rule functions, and task state transitions.
- What you can do after
- Build it from scratch by deriving valid states, enforcing them at boundaries, and selecting representations that exclude illegal states.
Read how Data-Oriented Programming in Java explains invariant →
Fabulous Adventures in Data Structures and Algorithms
An invariant is a property that remains true throughout the valid states or operations of a computation.
- How it is used
- Uses invariants to exclude invalid states and guide operations that construct persistent data structures or advance an algorithm.
- How deep it goes
- Works through invariant-preserving branches and implementations, including a deliberate relaxation for deque concatenation, without developing a general proof method.
- Examples
- Illustrates them with a two-stack queue, an expanding Life grid, a shared empty Hughes list, and incremental word-graph minimization.
- What you can do after
- Build it from scratch: design operations that preserve valid queue, deque, and graph states while ruling out unwanted cases.
Read how Fabulous Adventures in Data Structures and Algorithms explains invariant →
Clean Applications with Hexagonal Architecture
A condition that must remain true for a domain object or business state to be valid.
- How it is used
- Places business-validity decisions in a framework-independent domain core during migration to hexagonal architecture.
- How deep it goes
- Explains construction-time validation, domain state transitions, and aggregate-wide consistency, including the risks of validating after construction.
- Examples
- Uses article creation, author lookup, title validation, and draft-status enforcement to illustrate invariant ownership.
- What you can do after
- Build domain entities with validating factories and place state-change rules in domain operations.
Read how Clean Applications with Hexagonal Architecture explains invariant →
Unit Testing Principles, Practices, and Patterns
An invariant is a condition that must remain true for a software object or component.
- How it is used
- Uses invariants to evaluate whether an API preserves object rules without exposing implementation details.
- 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.
Read how Unit Testing Principles, Practices, and Patterns explains invariant →
Microservices Patterns, Second Edition
An invariant is a condition that must remain true for application data or system state to be valid.
- How it is used
- Uses invariants as correctness conditions that system commands and transactions must preserve across state changes.
- How deep it goes
- Defines transaction commit and abort conditions, then illustrates saga anomalies that violate invariants without detailing remedies.
- Examples
- Uses oversold inventory, customer credit limits, and concurrent create-order and cancel-order sagas.
- What you can do after
- Evaluate whether a transaction meets its required invariants and recognize saga interleavings that violate them.
Read how Microservices Patterns, Second Edition explains invariant →
Vibe Engineering
A software invariant is a property or condition that must remain true throughout specified program states or operations.
- How it is used
- Uses invariants to evaluate AI-generated code through executable properties, contracts, and adversarial tests.
- How deep it goes
- Defines invariants and demonstrates tests, but stops short of treating ordinary checks as mathematical proof.
- Examples
- Uses balanced parser tags, concatenated parser inputs, conserved link counts, and explicit parser preconditions and postconditions.
- What you can do after
- Diagnose AI-generated code with property-based tests that check structural, behavioral, and conservation constraints.
Learn Haskell by Example
An invariant is a property that must remain true for every valid state of a data structure or computation.
- How it is used
- Uses invariants to make associative maps dependable before building graph structures.
- How deep it goes
- Explains enforcement procedurally through newtype wrapping, export lists, and controlled map operations, while deferring newtype-versus-data subtleties.
- Examples
- Uses a duplicate-key list, AssocMap module exports, and GHCi insert-and-delete results.
- What you can do after
- Build it from scratch by encapsulating an associative map and exposing operations that preserve unique keys.
F# in Action: A Revised Edition of Get Programming with F#
An invariant is a condition that must remain true for a value or domain entity to be considered valid.
- How it is used
- Uses invariants to require validated domain values before email-sending code can run.
- How deep it goes
- Works through wrapper and private-construction patterns using a minimal “@” check, without specifying complete email validation.
- Examples
- Contrasts a customer email validity check with a private ValidatedEmail case created through Result and passed to sendEmailSafe.
- What you can do after
- Build it from scratch with a private F# union case and a Create method, then accept only validated values downstream.
Read how F# in Action: A Revised Edition of Get Programming with F# explains invariant →
Software Design for Python Programmers
The Class Invariant Principle states that a condition governing a class's valid objects must remain true during runtime.
- How it is used
- Prevents class methods from leaving objects in invalid states and reduces surprises for callers.
- How deep it goes
- Defines a Boolean state condition, implements runtime checks, and explains temporary mutation violations without covering native language support.
- Examples
- Uses a Python circular buffer whose head and tail indexes remain within the buffer capacity.
- What you can do after
- Diagnose/debug with it by asserting valid object state at construction and after state-changing operations.
Read how Software Design for Python Programmers explains invariant →
Object-Oriented Software Design in C++
A design principle stating that a class condition must remain true throughout the runtime of its objects.
- How it is used
- Uses object-state conditions with programming by contract to prevent invalid class instances and runtime surprises.
- 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 you can do after
- Evaluate object-state rules and diagnose invalid transitions by writing invariant checks and assertions for critical C++ classes.
Read how Object-Oriented Software Design in C++ explains invariant →
Functional Design and Architecture: Examples in Haskell
An invariant is a condition or property that remains true for every valid state or execution covered by its specification.
- How it is used
- Uses invariants to identify domain essence and turn pure-algorithm behavior into executable properties.
- How deep it goes
- Explains invariants through design abstractions and generated tests, but stops short of guaranteeing freedom from subtle logical bugs.
- Examples
- Uses structure-preserving list mapping and squaring-function properties, including generated counterexamples and shrinking.
- What you can do after
- Diagnose logic errors by expressing invariants as properties and testing them against generated inputs.
Read how Functional Design and Architecture: Examples in Haskell explains invariant →
Grokking GPU Programming
An invariant is a property that remains true at each stage of an algorithm.
- How it is used
- Uses a round-by-round property to justify the correctness of parallel scan algorithms.
- How deep it goes
- Derives scan invariants across Hillis-Steele rounds and Blelloch phases, including boundary cases and how the final prefixes follow.
- Examples
- Traces an eight-element array through Hillis-Steele rounds and describes growing ranges in Blelloch’s up-sweep.
- What you can do after
- Understand scan correctness by checking what each position represents after every round or phase.
Functional Programming in C#, Second Edition
An invariant is a condition that must remain true for a program object or system to be valid.
- How it is used
- Uses invariants to describe valid object state and motivate avoiding mutation under concurrency.
- How deep it goes
- Defines an inventory condition and explains how non-atomic updates expose temporary invalid states, without developing a general formal treatment.
- Examples
- Uses an inventory threshold and a shopping-cart total property as examples.
- What you can do after
- Apply property-based tests to encode model invariants, such as checking that removing cart items cannot increase its total.
Read how Functional Programming in C#, Second Edition explains invariant →
Advanced Algorithms and Data Structures
An invariant is an internal property of a data structure or mathematical object that remains true throughout a process or across permitted transformations.
- How it is used
- Uses internal properties to keep data structures faithful to their external API contracts during updates.
- How deep it goes
- Explains definition, API relationship, and structural maintenance through sorted lists, priority queues, and R-trees.
- Examples
- Uses sorted-list ordering, priority-queue guarantees, and R-tree occupancy and bounding rectangles as concrete examples.
- What you can do after
- Build it from scratch by stating invariants and designing update operations that preserve them.
Read how Advanced Algorithms and Data Structures explains invariant →
C++ Concurrency in Action, Second Edition
An invariant is a condition that remains true about a data structure or program state when it is in a valid state.
- How it is used
- Uses invariants to reason about the risks of modifying shared data between threads.
- How deep it goes
- Works through a doubly linked-list deletion and explains how separate updates temporarily break its invariant.
- Examples
- Uses doubly linked-list deletion and queue insertion to illustrate broken and preserved invariants.
- What you can do after
- Evaluate whether concurrent updates can expose a data structure while its invariants are broken.
Read how C++ Concurrency in Action, Second Edition explains invariant →
The Art of Code
An invariant is a condition that must remain true for a value or data structure to be valid.
- How it is used
- Uses invariants to protect domain data and reject invalid states early during data modeling.
- How deep it goes
- Defines validity conditions and placement principles, but stops short of language-specific implementation details.
- Examples
- Uses units, ranges, composite keys, exposed collections, nullable fields, and scattered validation as modeling examples.
- What you can do after
- Apply it by locating validity rules beside the data they protect and rejecting invalid states as early as possible.
Machine Learning System Design
The property of remaining unchanged under specified transformations or perturbations.
- How it is used
- Measures whether ML outputs remain dependable under expected input changes, repeated execution, and model releases.
- How deep it goes
- Defines transformation and retraining invariants, then connects them to consistency metrics and property-based tests without deriving implementation formulas.
- Examples
- Uses lighting, synonyms, image rotation, image scaling, audio volume, house size, and antifraud releases as test scenarios.
- What you can do after
- Diagnose/debug with it by defining expected perturbations and checking whether predictions remain stable through consistency metrics and generated tests.
Read how Machine Learning System Design explains invariant →
Also covered in
- Troubleshooting Java, Second Edition
- 100 Java Mistakes and How to Avoid Them
- Collaborative Software Design: How to facilitate domain modeling decisions
- The Coder CafeIn early access (MEAP)
- Authorization in Action
- Simple Object-Oriented Design: Create clean, maintainable applications
- Grokking Data Structures
- Julia as a Second Language
What to know first
- contractA contract is an agreed specification of the conditions, expectations, rights, or obligations that govern behavior or interactions between parties or software components.
- business ruleA business rule is a domain-specific constraint, policy, or decision criterion that governs valid data, behavior, decisions, or processes.
- exceptionAn exception is a runtime signal or value representing an abnormal condition that interrupts ordinary program flow and can be handled or propagated.
- stateState is information describing the condition or configuration of a system or computation at a particular time that may influence its behavior or subsequent transitions.
Related concepts
- property-based testingused by · Property-based testing is a software-testing technique that checks whether specified general properties hold across varied, often automatically generated, inputs.
- illegal stateaddresses · An illegal state is a program or system state that violates constraints required by its data model, domain rules, or specification.
- contractpart of · A contract is an agreed specification of the conditions, expectations, rights, or obligations that govern behavior or interactions between parties or software components.
- accessor methodconfigured by · An accessor method or function is a callable that reads, computes, or assigns a value associated with a property, field, or data element.
- aggregateaddressed by · A domain-driven design aggregate is a cluster of related domain objects treated as a unit for consistency and state changes, typically accessed through a designated root.
- attributekind of · An attribute is a named property or piece of information associated with an entity, object, or structured data item.
Questions about invariant
What is invariant?
An invariant is a condition or property that must remain true across the specified valid states, operations, or transformations of a system or computation.
Which Manning books explain invariant?
100 C++ Mistakes and How to Avoid Them, Data-Oriented Programming in Java, Fabulous Adventures in Data Structures and Algorithms, Clean Applications with Hexagonal Architecture, Unit Testing Principles, Practices, and Patterns, Microservices Patterns, Second Edition, Vibe Engineering, Learn Haskell by Example and 10 more.
What should I know before learning invariant?
Manning books that teach invariant usually introduce contract, business rule, exception and state first.
What is invariant a kind of?
Invariant is a kind of attribute. An attribute is a named property or piece of information associated with an entity, object, or structured data item.
What is invariant part of?
Invariant is part of contract. A contract is an agreed specification of the conditions, expectations, rights, or obligations that govern behavior or interactions between parties or software components.
What is invariant also called?
Invariant is also called invariance.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

















