views:

434

answers:

4

Is that any library that aids in implementing design by contract principle in c++ application. EDIT:

Looking for much better than ASSERT something like this

+4  A: 

Simplest?

Assert statements at the start of your function to test your requirements. Assert statements at the end of your function to test your results.

Yes, it's crude, its not a big system, but its simplicity makes it versatile and portable.

SPWorley
Something better than this http://www.codeproject.com/KB/cpp/DesignByContract.aspx
yesraaj
And the major feature of DbC - that pre/postconditions are inherited - will not be emulated by Assert.
Tobias Langner
Also "at the end of your functions" becomes very complex when you use "return" in few places. Not to mention exceptions.
Adam Badura
True, you should at least use asserts at the beginning and each time you get data from elsewher (non-local) like when you get a pointer, you have to check that it's valid, when you get some values you have to check that they match your assumptions etc. The beginning asserts should purpose is to check the context of the function call, the other asserts check the assumptions about the extern data and the local operations.
Klaim
A: 

assert.h

Martin v. Löwis
+3  A: 

I followed the teachings of the following articles:

An exception or a bug? (Miro Samek)

Simple Support for Design by Contract in C++ (Pedro Guerreiro)

What I ultimately applied was very much Samek's approach. Just creating macros for REQUIRE, ENSURE, CHECK and INVARIANT (based on the existing assert macro) was very useful. Of course it's not as good as native language support but anyway, it allows you to get most of the practical value from the technique.

As for libraries, I don't think that it pays to use one, because one important value of the assertion mechanism is its simplicity.

For the difference between debug and production code, see When should assertions stay in production code?.

Daniel Daranas
+2  A: 

Hi,

Some design patterns, such as the non-virtual interface make it natural to write pre/post-conditions for a given method:

#include <cassert>

class Car {
    virtual bool engine_running_impl() = 0;
    virtual void stop_impl() = 0;
    virtual void start_impl() = 0;

    public:
    bool engine_running() {
        return engine_running_impl();
    }

    void stop() {
        assert(engine_running());
        stop_impl();
        assert(! engine_running());
    }

    void start()
    {
        assert(! engine_running());
        start_impl();
        assert(engine_running());
    }
}


class CarImpl : public Car {
    bool engine_running_impl() {
        /* ... */
    }

    void stop_impl() {
        /* ... */
    }

    void start_impl() {
        /* ... */
    }
}
David Wilson