FAQ 10.08 Why should the invariant be captured explicitly?

graphics/new_icon.gif

As maintenance documentation and to catch bugs.

The class invariant should be recorded, if for no other reason than as documentation for future maintainers. Since a developer's job isn't done until the internal constraints of the data structure have been properly documented, there is really no choice. Someone somewhere has to write down these internal constraints.

If the internal constraints of the class's data structure are to be documented, the most natural and accessible place is along with the class's code. And source code is the most unambiguous way to express this documentation since expressing it in a natural language is relatively imprecise.

Plus, if the invariant is captured in a member function, the member function can be called at strategic moments during an object's life cycle, which effectively tests the documentation as well as testing the class's member functions. In other words, this technique makes sure that the invariant is correct and makes sure that the other member functions don't violate the invariant. If desired, these calls to the invariant can be placed in an #ifdef or an assert() so they can easily be removed before the software is shipped.

In cases where a class has a nontrivial invariant, practical experience has shown that this can catch a sizeable percentage of a class's bugs.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net