< previous page page_360 next page >

Page 360
Class Invariants
Most classes have some conditions that should always be true whenever you are finished with a class member function. These class invariants are the sine qua non of your class. For example, it may be true that your CIRCLE object should never have a radius of 0, or that your ANIMAL should always have an age greater than 0 and less than 100.
It can be very helpful to declare an Invariants() method that returns true only if each of these conditions is still true. You can then insert Assert(Invariants()) at the start and completion of every class method. The exception would be that your Invariants() would not be expected to return true before your constructor runs or after your destructor ends. Listing 21.4 demonstrates the use of the Invariants() method in a trivial class.
LISTING 21.4 USINGInvariants()

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:   #define DEBUG
2:   #define SHOW_INVARIANTS
3:   #include <iostream.h>
4:   #include <string.h>
5:
6:   #ifndef DEBUG
7:   #define ASSERT(x)
8:   #else
9:   #define ASSERT(x) \
10:   if (! (x)) \
11:    { \
12:       cout << ERROR!! Assert  << #x <<  failed\n; \
13:       cout <<  on line  << __LINE__ << \n; \
14:       cout <<  in file  << __FILE__ << \n; \
15:    }
16:   #endif
17:
18:   class String
19:   {
20:   public:
21:      // constructors
22:      String();
23:      String(const char *const);
24:      String(const String &);
25:      ~String();
26:
27:      char & operator[](int offset);
28:      char operator[](int offset) const;
29:
30:      String & operator= (const String &);
31:      int GetLen()const { return itsLen; }
32:      const char * GetString() const { return itsString; }
33:      bool Invariants() const;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_360 next page >

If you like this book, buy it!