Shortcut evaluation for hierarchy of in contracts

simendsjo simendsjo at gmail.com
Fri Jul 1 16:51:16 PDT 2011


On 02.07.2011 01:32, Robert Jacques wrote:
> On Fri, 01 Jul 2011 02:39:29 -0400, Jens Mueller <jens.k.mueller at gmx.de>
> wrote:
>> Robert Jacques wrote:
>>> On Thu, 30 Jun 2011 06:42:57 -0400, Jens Mueller
>>> <jens.k.mueller at gmx.de> wrote:
>>>
>>> >bearophile wrote:
>>> >>Jens Mueller:
>>> >>
>>> >>> 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
>>> >>> }
>>> >>
>>> >>I think it's a DMD bug, fit for Bugzilla if not already present.
>>> >
>>> >The shortcut evaluation is specified in TDPL. That's why I assume the
>>> >behavior is intended.
>>> >
>>> >Jens
>>>
>>> A subclass must be able to handle all the inputs the base class
>>> accepts, otherwise it isn't true polymorphism anymore. Not being
>>> able to use Sub where Base is expected, and maybe only Base was
>>> tested, can lead to major bugs.
>>
>> So you agree that the current behavior is error-prone?
>
> No. I think the current behavior is correct. In fact, if anything, D
> shouldn't allow you to define an in contract on any override method. A
> Sub is a Base and therefore must be able to handle all inputs that are
> valid for a Base.

Have to agree. By tightening the contracts in subclasses, you'll break 
Liskov substitution principle.


More information about the Digitalmars-d mailing list