Invariant

In software, an invariant is a requirement made about the state of a program that never changes. It is often possible to force requirements on data simply by structuring the data such that breaking the requirement is impossible. The base array in most programming languages will never lose its transitivity—the property that if a comes before b, which comes before c, then a must come before c. If a programmer was to create their own ordered collection, however, they would need to enforce the invariant of transitivity themselves.

An invariant is a strong indicator that a new layer of abstraction is required. If a to-do list is also an ordered collection, and that ordered collection has many requirements that have little to do with task lists specifically, it might be time to create a new, custom ordered list. The new collection could then be tested separately and extensively for bugs.

Assertions in production code can be used to track the compliance of data with an invariant. An assertion checks for a condition, and alerts a programmer when that condition fails. The outcome of a failing assertion is configurable. It isn't necessarily the same as throwing an error, though that can be the case. During testing, it is recommended that failed assertions alert the programmer directly; either by interrupting the program or through a logger.

Invariant assertions bring up a difficult question: how do you handle an error in production that is never intended to happen? When a service request fails the state of the program is not presumed to be corrupted, and it should be expected to continue functioning once the network issue has cleared. But a failed invariant is often an indicator of corrupted state—a particularly pervasive type of bug, which might require resetting part or all of the program state.

If the software is transactional, the transaction which broke the invariant can be aborted, and its effect nullified. But if the software is imperative, any corrections would need to be custom. As an invariant is never expected to break in production, the benefits of preparing for such an event are questionable. It is likely that only the most critical of software should bother to defend against a broken invariant.

#software