Re: Applying contracts to abstract base class?

From: Stefan (stefan_at_unfunked.org)
Date: 10/28/03

  • Next message: Uncle Bob (Robert C. Martin): "Re: Visitor, dynamic_cast or ..."
    Date: Tue, 28 Oct 2003 12:42:40 +0000
    
    

    Ken wrote:
    > Hi. I'm looking to find a way to apply Design by Contract in my C++
    > programs.
    > %<
    > Is there a way for C++ to somehow enable an interface base class to
    > enforce its contracts? Seems like an unfixable paradox.
    >

    I wonder if it would be a good idea to define your pre/postconditions
    and invariants in the class header using #defines. For example:

    class Thing
    {
    public:
        void Method();
        #define Thing_Method_PRECOND \
           condition && other_condition
    };

    void Thing::Method()
    {
        ASSERT(Thing_Method_PRECOND)
    }

    It seems to me that there are two advantages to this approach. First,
    the contracts are stated with the interface of the class, where the
    developer is most likely to want to read them. Second, it is possible to
    include the conditions of the superclass in the #define so there's no
    need to duplicate the logic.

    This should solve your abstract base class problem since the contracts
    need not be implemented (ASSERTed) until they are used in a concrete
    method. The only irritating problem is the length of the #define names
    which must be unique.

    Just a thought! I'll try this out on my next project.

    Stefan


  • Next message: Uncle Bob (Robert C. Martin): "Re: Visitor, dynamic_cast or ..."

    Relevant Pages