Shortcut evaluation for hierarchy of in contracts

Jens Mueller jens.k.mueller at gmx.de
Thu Jun 30 03:02:18 PDT 2011


Hi,

a student of our seminar observed a questionable behavior when checking
in contracts/pre conditions in a polymorphic hierarchy.
When checking in contracts for polymorphic classes they are verified
starting at the base class but with shortcuts. I.e. the first in
contract that works causes to skip executing of following contracts.
This is perfectly valid because in contracts are only allowed to
require less. But what if the programmer fails to follow this rule? Why
not checking all in contracts. Since contracts are compiled out in
release mode I argue it's worth the extra cycles to detect some
inconsistency in the contracts. Polymorphic hierarchies can be deep.
Consider the following example

check_require_less.d:
unittest {
    class Base {
        void foo(uint i)
            in { assert(i <= 10); }
        body { }
    }
    
    class Sub : Base {   
        override void foo(uint i)
            in { assert(i <= 5); } // fails to require less but I won't know
        body
        {
            assert(i <= 5); // fails here because in contract wasn't checked
        }
    }
    
    auto s = new Sub;
    //s.foo(10); // fails as expected
    s.foo(7); // due to shortcut evaluation of in contracts this call passes all contracts
}

$ rdmd --main -unittest check_require_less.d

In the case above s.foo(7) will fail but this is only due to the fact
that I recheck the contract. If I wouldn't s.foo() may be executed and
the programmer assumes that i <= 5 holds. Thus, s.foo() gets executed
based on wrong assumptions. Hence, s.foo() may not work properly. A fact
that is hidden from the programmer.

Jens


More information about the Digitalmars-d mailing list