enforce()?

Norbert Nemec Norbert at Nemec-online.de
Mon Jun 28 01:15:05 PDT 2010


On 19/06/10 22:46, Andrei Alexandrescu wrote:
> On 06/19/2010 03:55 PM, bearophile wrote:
>> Inside Phobos2 I have counted about 160 usages of the "body" keyword.
>> I think contract programming can be used more often inside Phobos2
>> (and maybe some usages of enforce() can be turned into contract
>> programming because they are more similar to program sanity checks).
>
> Walter and I discussed this and concluded that Phobos should handle its
> parameters as user input. Therefore they need to be scrubbed with hard
> tests, not contracts.

IMHO, this is plain wrong!

By this kind of decision, you are putting the library user under 
tutelage. The D language is explicitly designed to allow the user to 
take off the safety belt, but to do so at their own responsibility. I 
typically get very annoyed out of principle if I explicitly and 
consciously switch *off* a safety feature and someone decides that they 
do not trust that I am mature enough for that decision and leave part of 
the safety checks in place.

The interface between parts of a program is exactly what contracts are 
designed for. Calling a function with incorrect arguments is a bug in 
the calling code. It should be caught at the interface by a contract 
violation. If the library user trusts their program enough to switch off 
contract checking, the library designer should not worry about 
double-checking for incorrect function calls.

Contracts are part of the public interface, so whatever is specified 
there is automatically documented for the world to see. Replacing 
contracts by "enforce" statements inside the library functions means 
that you have to document in prose what kind of input arguments are allowed.

There are exceptional cases when exceptions may be thrown for incorrect 
arguments: typically, whenever testing for input correctness would be 
too costly, e.g. for badly conditioned matrices in linear algebra code. 
Here, the problem typically shows up during the calculation when it is 
too late to issue a contract violation.

Otherwise, exceptions in library code should only happen in well-defined 
cases for run-time conditions (like I/O errors).

Sorry about by blunt words, but I feel that behind this issue there 
still is a rather fundamental misunderstanding of the concepts of 
contract programming.


More information about the Digitalmars-d mailing list