Preserve class invariants

An invariant is an assertion about an object's internal state. Such assertions are helpful in making sure that the object transitions from one valid state to another and that it meets the behavioral promises of its interface.

To preserve class invariants:

A good Taligent illustration of all three points is TStream, which encapsulates a concept of a logical end of stream. The invariant is simply that the class represents the correct logical end of stream.

The inline write functions of TStream modify the current position in the stream without checking the logical end. Thus, the class must catch up whenever it next gets a chance (that is, when a virtual function gets called). TStream must then infer the new logical end from the new stream position and other data members. If the computation is not performed immediately, that information can change again, and the new logical end will not be correctly computed.

In summary, learn what your invariants are and strive to keep them correct. The Assert function from the Test framework is very helpful. It allows you to test invariants when testing is turned on, but skips the check otherwise. If even that is too expensive, you can conditionally compile your assertions for debugging.


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker