Good Contract programming idiom?

bearophile bearophileHUGS at lycos.com
Tue Mar 2 12:54:45 PST 2010


Kagamin:

> Never deemed -release flag as a useful thing, may be I just don't put in useless asserts?

-release disables array bounds tests too. This can produce D code 2-3 times faster if you process array a lot, because DMD is not (as recent versions of Java HotSpot) able to infer many situations where it can remove them. Future D compilers able to do what HotSpot does, will have less need of -release mode.
(With LDC you can disable just array bound tests and keep asserts, if you want).


> And I don't think that detailed exceptions do a lot more than simple asserts. Job is done faster with simple assert and I don't see much difference between
> IllegalArgumentException: wrong day
> and
> day>=1 && day<=31 assertion failed
> Though the former may create better image for your library.

That was a silly and very simple example, where there's no real need of an error message.
But there are many situations where giving a better error message is very useful, because it can become quite less easy to understand why an assert has failed and why testing such assert in this part of code is important to assure the correct successive operations done by the code.
Note that D asserts/enforces have an optional string for error message, just like exceptions :-)


I have modified a little the second D version, using enforce() and I have improved the text that explains this comes from practical considerations (while I think in theory right Michiel Helvensteijn is right):
http://en.wikipedia.org/wiki/Class_invariant#D

Bye,
bearophile



More information about the Digitalmars-d mailing list