alwaysAssert() [was: Against enforce()]

dsimcha dsimcha at yahoo.com
Thu Mar 17 12:32:39 PDT 2011


== Quote from Walter Bright (newshound2 at digitalmars.com)'s article
> On 3/16/2011 6:07 PM, Andrei Alexandrescu wrote:
> > On 03/16/2011 06:45 PM, bearophile wrote:
> >> So a better solution is for the standard Phobos library to ship in two
> >> versions, one compiled in release and not release mode, and DMD may choose the
> >> right one according to the compilation switches. This removes most of the need
> >> of enforce(). I suggest to deprecate enforce(). Until the problem with Phobos
> >> compilation is solved and enforces are removed from Phobos, enforce() may
> >> become a private Phobos function that user code can't import.
> >
> > There may be some confusion somewhere. enforce is not supposed to be a sort of
> > assert. It is a different tool with a different charter. Use assert for
assertions.
> I want to emphasize Andrei's point.
> 1. Asserts and contracts are for detecting program BUGS. They are not for
> validating user input, checking for disk full, file not found errors, etc.
> 2. Enforce is for validating user input, checking for disk full, file not found
> errors, etc. Enforce is NOT for use in contracts or checking for program bugs.
> Any use of enforce in Phobos that is checking for program bugs is itself a bug
> and should be entered into bugzilla for fixing.

I've asked for this before and I'll ask again:  Can we **please** put an
alwaysAssert() function (or an abbreviation of this to make it less verbose) in
Phobos?  I proposed this once before and it wasn't well liked for some reason
This reminded me to persist a little about it.

I sometimes abuse enforce() for non-performance critical asserts that I don't want
to ever be turned off, but that are semantically asserts in that they're supposed
to reveal bugs, not check for within-spec errors.  I know this is The Wrong Thing
to do, but it's too convenient and useful to stop doing it unless I have a good
alternative.  The differences between enforce() and alwaysAssert() would be that
alwaysAssert() throws an AssertError instead of an Exception and that they
indicate different intents.  alwaysAssert() could even be implemented in terms of
enforce() using custom exceptions.

Example implementation:

void alwaysAssert(T, string file = __FILE__, string line = __LINE__)
(T value, lazy string msg = null) {
    enforce!(T, file, line)(value, new AssertError(msg));
}


More information about the Digitalmars-d mailing list