In software engineering, a explicit logical statement that must evaluate to true
at all externally observable times during the lifecycle of a method or component.
(Compare with precondition and postcondition). "Externally observable" is an
important qualifier, since the component's regular operation may require several
steps, between which the invariant is not necessarily satisfied. In the
design by contract paradigm, pioneered by the Eiffel language, invariants
are embodied as formal assertions that are tested on the entry and exit
of a method. Failure of an invariant can denote an error either by the "client" or
the "supplier", and places no guarantees that the component still
functions as designed.
In complex application software, an invariant represents a known consistent
state of an object, or complex data structure of objects. In a database,
for example, relational constraints must be maintained, often
through transaction management. However, invariants have a role to play in much
smaller components. They can be used to guard against possible corruption of an
object, and calculations based on invariants may be moved out of iterative
code during optimization.
Violations in invariants are often used as detection for
race conditions in
multithreading environments. Without a suitable synchronization mechanism, one
thread of execution operates on the object while in a state where it should not
be externally observable. The invariant, and hence the behavior of the object, cannot
be guaranteed under these conditions.