invariant

A rule that must always hold for an object or system, such as a count never being negative.

In more detail

A broken invariant means the program has a bug and its state can no longer be trusted. Enforcing invariants where objects are created means no invalid instance ever exists, and when an invariant spans several values that concurrent code updates, a lock or a single owner must protect it. Problems that can happen in normal operation, such as a missing file or an unreachable host, are not invariants and should be handled as ordinary errors.

Examples

In AWS: A rule about the data that must always hold true, such as an account balance never going below zero.
Go: a broken invariant may panic; expected failures return an error
Java: a record's compact constructor throws IllegalArgumentException when itemCount is negative.

Related terms

Taught in

References