The rules that dictate how the member variables of a class represent a value (such as a bag of items) are called the invariant of the class.
The knowledge of these rules is essential to the correct implementation
of the class's functions. With the exception of the constructors, each
function depends on the invariant being valid when the function is
called. And each function, including the constructors, has a
responsibility of ensuring that the invariant is valid when the
function finishes. In some sense, the invariant of a class is a
condition that is an implicit
part of every function's postcondition. And (except for the
constructors) it is also an implicit part of every function's
precondition. The invariant is not usually written as an explicit
part of the preconditions and postconditions because the programmer who
uses the class does not need to know about these conditions. But to the
implementor of the class, the invariant is indispensable. In other
words, the invariant is a critical part of the implementation of a
class, but it has no effect on the way the class is used.
|