In object oriented computer programming and design, a class invariant is a set of rules that can be used to define whether an object instance exists in a valid state. From a design perspective, it is a set of boundaries between which the data within an object must fall to be considered in a proper, functional state. It can be defined in design documentation or source code comments or, in some programming languages, can be directly implemented in actionable computer code. A program that uses coded invariants and assertions can cause the program to cease execution or throw various errors when the invariant conditions are not met. Unlike standard error checking, class invariants generally are used only for the purpose of ensuring that the inner implementation of a class is functioning, and they usually are not listed in public documentation or programming interfaces.
From a very basic level, a class invariant essentially is a collection of assertions for a class. An assertion, again in simple terms, is a statement that checks some part of the state of the class and must evaluate to true for program execution to continue. One example of an assertion is a statement that ensures a given integer is always between 1 and 10. When a class invariant is used, assertions are evaluated for all relevant parts of the data held by the object, essentially validating that all the data in the object are within the defined ranges.
In many instances, using a class invariant strongly resembles standard error checking, in which variables are measured to ensure they are within usable boundaries or are not null. The difference between using class invariants and standard error checking, however, is that invariants and assertions are predominantly used to capture errors that should not occur unless there is an intrinsic flaw in the code. Another difference is that standard error checking tends to involve recovery and changes in program control flow, whereas the result of an invariant failure should be program termination. The reason most programs terminate when a class invariant check fails is because the object is in a compromised state and is unable, from a design view, to fulfill its preconditions and post-conditions necessary to adhere to its design contract.
One of the properties of a class invariant in object oriented programming languages in which they are implicitly defined is that the invariant is a mechanism inherited by any subclasses. This prevents a subclass from overriding any invariant checks that are performed in the parent class. Ultimately, this means a subclass is unable to break the design contract established by the superclass, which could cause unpredictable results or hard-to-find program errors.