TITLE: Support for class invariants [ This tip is related closely to the concept of "programming by contract", discussed at length in "Object Oriented Software Construction", by Bertrand Meyers. The basic idea is that a server function imposes a set of requirements on the client. If the client meets those requirements, the server function will guarantee certain state when the function executes. These initial requirements are called "preconditions" and the guarantees are called "postconditions". If a client violates preconditions, it is the client's problem (ideally handled with exceptions), not the server's. In addition to pre and post conditions, a class with methods might have invariants, conditions which should hold true outside a given method's scope AND at the beginning and ending of the method. -adc ] PROBLEM: ulal@stud.uni-sb.de (Ulrich Alt) ... But is there a way to express *class invariants*, i.e. conditions, that must be fulfilled each time an exported (public) member function was called ? [ I think he means, is there an automatic, compiler-supported mechanism for invariants. -adc ] RESPONSE: clamage@taumet.Eng.Sun.COM (Steve Clamage), 3 Jul 94 Of course. Write a condition as (for example) an inline member function and invoke it from each appropriate member function. Example: class Stack { T *data; int index; size_t size; public: void class_invariant() { if( index > size || index < 0 ) throw error; } void push(T& val) { class_invariant(); ... } T& pop() { class_invariant(); ... } ... }; You can also also write pre- and post-conditions and invoke them from member functions. A pre- or post-condition would normally include the class invariant. You can use conditional compilation or rely on dead-code elimination to turn off checking. I like to keep in mind C.A.R. Hoare's comment that turning off run-time checks in production code is like keeping a fire extinguisher in the car except when you take it on the road.