optional feature with contract inheritance? (design question)

Lutger lutger.blijdestijn at gmail.com
Sat Feb 27 08:56:36 PST 2010


What do you think of the following use of contracts?

class Base
{
    void useFeatureA()
    in { assert(false, "Base does not implement feature A"); }
    body
    { 
        /* throw here? */ 
    }

    bool hasFeatureA()
    {
        return false;
    }
}

class Derived : Base
{
    override void useFeatureA()
    in { assert(true); }
    body 
    { 
        /* do feature A */ 
    }

    override bool hasFeatureA()
    {
        return true;
    }
}

In .NET this is supposedly called the optional feature pattern, recommended 
to use if you want to prevent factoring into too many interfaces. In .NET 
A.useFeatureA would just throw of course. 

Adding preconditions to functions in a derived class loosens the contract, or 
adds to the set of acceptable inputs so to speak. In this case, the 
polymorphic type of the object is considered as the (sole) input. 

Does it make sense? Is this a good/bad/ugly way of using contracts?


More information about the Digitalmars-d-learn mailing list