Class invariant
|
This article is about class invariants in computer science; for use of the term in mathematics, see equivalence class and invariant.
In computer science, a class invariant is an invariant used to constrain objects of a class. Methods of the class should preserve the invariant. The class invariant constrains the state stored in the object.
Class invariants are established during construction and constantly maintained between calls to public methods. Temporary breaking of class invariance between private method calls is possible, although not encouraged.
Example
This is an example of a class invariant in D. The invariant must hold to be true after the constructor is finished, before the destructor gets called, and at the entry and exit of all public member functions.
class Date { int day; int hour; invariant { assert(1 <= day && day <= 31); assert(0 <= hour && hour < 24); } this(int d, int h) { day = d; hour = h; } }