Good Contract programming idiom?

Norbert Nemec Norbert at Nemec-online.de
Thu Mar 4 01:29:33 PST 2010


Brad Roberts wrote:
> On Wed, 3 Mar 2010, Norbert Nemec wrote:
> 
>> The edited Wikipedia text for D is so far correct, even though the whole page
>> is not quite as precise as it could be. The theoretical basis and the
>> practical application are somewhat mixed. Fixing that, however, would be a
>> major task.
>>
>> I think the fundamental distinction between three concepts is essential in
>> understanding the issue:
>>
>> * exceptions - handling of run-time conditions caused by user, file, network
>> or any other kind of input. Hitting an exception is not a bug but a regular
>> function of the code.
>>
>> * contracts - well designed parts of interfaces. Best understood literally as
>> "contract", defining who is responsible for a bug. The possibility to check a
>> contract at runtime is actually a secondary function.
>>
>> * assertions - best understood as "comments" that can be checked by the
>> compiler. Sprinkle them freely wherever you find some non-trivial relation
>> between variables of the code.
>>
>> I guess this whole issue simply is something that has to be discussed more
>> frequently to make people aware of it.
>>
>> Greetings,
>> Norbert
> 
> There's an important point that's been left out of this conversation so 
> far (unless I missed it):
> 
> Asserts in the body of a method have no impact on overridden 
> implementations in subclasses, but in/out contracts do.  So there's a 
> distinct value in using in/out for non-final methods.

Perhaps, I should have been more precise in what I meant with the words 
"well designed parts of interfaces":

If you study the original design of Eiffel by Bertrand Meyer, you will 
find that classes are strictly separated into interface and 
implementation. Contracts are part of the interface, so they are indeed 
inherited. When overriding a method, the input contract ("demands") can 
only be relaxed while the output contract ("promises") can only be 
tightened so that whichever code is correct in using the parent class is 
still correct using any inheriting class.

To allow full support of Contract Programming in D, interfaces should 
allow contracts as well. For overriding methods the input contract 
should be "or"ed with the parents contracts while the output contract 
should be "and"ed with the parents contracts.



More information about the Digitalmars-d mailing list