assume, assert, enforce, @safe

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 30 23:57:18 PDT 2014


On 7/30/2014 3:39 PM, Joseph Rushton Wakeling via Digitalmars-d wrote:
> My take is that, for this reason, these should be asserts and not enforce()
> statements.  What are your thoughts on the matter?

An excellent question.

First, note that enforce() returns a recoverable exception, and assert() a 
non-recoverable error.

Logically, this means that enforce() is for scrubbing input, and assert() is for 
detecting program bugs. I'm pretty brutal in asserting (!) that program bugs are 
fatal, non-recoverable errors. I've been fighting this battle for decades, i.e. 
repeated proposals by well-meaning programmers who believe their programs can 
safely recover from an unknown, invalid state.

Pragmatically, enforce() is significantly more expensive as it uses the GC and 
callers must support exception safety. Also, take a look at the quantity 
generated code for the enforce() in the examples, and see how expensive it is. 
All those lovely messages generate a lot of bloat.

Phobos functions that are designed to scrub input must document so. Otherwise, 
they should assert.

For LinearCongruentialEngine() and initialize(), passing invalid arguments are 
programming bugs, and so they should be asserting.


More information about the Digitalmars-d mailing list