Against enforce()

Jonathan M Davis jmdavisProg at gmx.com
Thu Mar 17 14:01:06 PDT 2011


On Thursday, March 17, 2011 12:22:00 Walter Bright wrote:
> On 3/16/2011 6:53 PM, bearophile wrote:
> > Right. But saying just that is not enough. You have to add that such "if
> > (!condition) throw new Exception(args)" idiom is common in Phobos because
> > Phobos is present only in release mode. If the zip distribution of DMD
> > contains two Phobos and dmd becomes able to use the right one according
> > to the compilation switches, then I think that "if (!condition) throw
> > new Exception(args)" will become more rare, and the enforce() too will
> > be less commonly needed.
> 
> I must reiterate that enforce() is NOT FOR DETECTING PROGRAM BUGS.
> Therefore, enforce() must not change its behavior based on "release mode"
> or other compiler switches.
> 
> Contracts and asserts are for program bug detection. NOT enforce.
> 
> This distinction is critical.

I completely agree with you. However, I think that part of the confusion is that 
there was discussion of using enforce in Phobos in some cases where we might 
otherwise have used an assertion, because the assertions would general be 
compiled out when anyone went to use Phobos other than Phobos itself, so they 
would be useless. I'm not aware that ever actually having been done, however. 
And in general, I don't like the idea of using assertions to validate that 
someone is using a library function correctly rather than validating the library 
function itself. I really think that that should be treated like user input and 
throw an exception if it really is supposed to be being validated. Some 
additional assertions which could be of benefit both in unit testing and if some 
actually uses a non-release version of Phobos might be useful, but counting on 
that sort of check being there makes no sense to me. Assertions are for 
validating the code that they're in, not someone else's code which is using that 
code.

In any case, I think that part of the confusion here is due to previous 
discussions on the lack of assertions in -release (and the fact that libphobos.a 
is normally compiled with -release) and the possible use of enforce to get 
around that in some cases. I'm not aware that actually ever having been done, 
however.

Still, I do get the impression the people often confuse the purposes of 
assertions and exceptions.

- Jonathan M Davis


More information about the Digitalmars-d mailing list