Monday, April 17, 2006

Class Invariants in C++

Class invariants is consistency checks that is written as a method. That method is called when every normal entrance and exit from the function. Let's write class invariants simply. This page which my site introduces every time shows the following code:

class A {
public:
#ifdef DBG
virtual void invariant() { ...contracts... }
#endif
void foo();
};

You should write a code that call invariant at inside of the function.

void A::foo() {
#ifdef DBG
invariant();
#endif

...

#ifdef DBG
invariant();
#endif
}

This page recommends that you use a template to include macro lines. That's smart means.

template
inline void check_invariant
(T& iX)
{
#ifdef DBC
iX.invariant();
#endif
}

void A::foo()
{
check_invariant(*this);
...
check_invariant(*this);
}

A simple invariant can be realized in this way. But, you must work so much to achieve DbC completely because DbC of D programming language is more excellent.

No comments: