wikipedia上class invaraint的定义:
In computer programming, specifically object-oriented programming, 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.
这个定义以及后面的几个例子中的invariant是针对状态的,比如:Date类的month属性是1到12的整数。而我认为这里忽略了一种非状态的class invariant,比如:Pair类应该有这样的invariant:
Pair(x, y).Left() == x, Pair(x, y).Right() == y
其中,Pair()是Pair类的构造函数,Left(),Right()分别是取左、右值。这种非状态的,描述抽象数据类型构造和使用关系整体规范的class invariant似乎无法通过在类内部通过进行状态检查来保证,而单元测试时则应该明确并重点测试这样的invariant。