Slashdot Mirror


Design by Contract in C++?

An anonymous reader asks: "I have read some of the stuff on Eiffel, watched their tutorial videos about design by contract, and the entire thing sounds like a pretty good idea. However, the problem is that we don't use Eiffel at work, and I highly doubt I could get people to come around to the idea of switching to it. Although we use a lot of C++, I can imagine that a lot of the ideas from Eiffel can be applied there. I have looked around on the net and found a few articles talking about different ways of applying design by contract using assert statements and the like. I also found the dlib C++ library on SourceForge which, among other things, puts a design by contract face on a lot of API calls. So, there are obviously people doing it. What is everyone's experience with Design by Contract in C++? What tools are there that help make it a workable system? Lastly, are there any pitfalls to taking this approach in C++?"

3 of 114 comments (clear)

  1. Simple Solution - Violence by Anonymous Coward · · Score: 5, Funny

    I place a one line comment above each of my C++ functions that I want to have Eiffel like design by contract features:

    - // Note: If you don't pass reasonable values to this function I will fucking kill you
    -
    - void
    - DoSomething(...)
    - {
    - }

    PS F Ghandi

  2. Re:In C++ by bheilig · · Score: 5, Insightful

    Here are some pitfalls you might run into:

    1. Real DBC inherits the contracts from ancestor versions. Preconditions are or-ed together and postconditions are anded together. Invariants are also anded together. If you just use assertions you won't get this.

    2. Eiffel allows you to disable the run-time execution of contracts at a fine level of detail. Again, if you use assertions you can only enable all or disable all.

    3. There is no 'old' keyword in C++. Therefore you can't use 'old' in assertions.

    4. According to DBC, a routine is in a transitional state during the execution of a routine. What happens if a routine calls another routine in the same class? Should it check the invariant? The answer is no. There are other cases as well.

    5. It's difficult to implement a loop variant with an assertion. Not a big deal since most Eiffel code I've seen doesn't use loop variants.

    If you don't want to use assertions, you can try some of the class pre-processors that are out there. You will see mixed results. In particular, I don't know of one that can handle 4. This is a show stopper.

    I think you only have two choices. Use Eiffel or don't use contracts.

    Brian

  3. Re:I don't understand the question... by Haeleth · · Score: 5, Funny

    Perl isn't a programming language, it's a natural language that is somehow parsed by the compiler

    I must strongly object to your use of the term "natural" in that statement.