assert() vs. enforce(), invariant() vs. ... ?

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Thu Aug 29 04:19:35 PDT 2013


Hello all,

Within std.random there are various constructs, such as RandomCover or 
RandomSample, where it's desirable for the internal state not to be initialized 
until right before the first call to .front (or one of the other public 
methods).  Some rationale is given here:
http://forum.dlang.org/post/mailman.581.1377772931.1719.digitalmars-d@puremagic.com
http://d.puremagic.com/issues/show_bug.cgi?id=10322

Now, this raises a general question for me.  Within code we have two alternative 
means of error-checking -- assert(), for checking for logical errors in 
pre-release code, and enforce(), for essential checks that must be enforced even 
in release code.

We have an equivalent to assert() for structs/classes in the form of 
invariant(), which will make various checks at entry and exit to public 
functions, but -- if I'm not wrong -- this gets discarded in -release mode.

So, is there a case for an equivalent to enforce() -- something that will 
_always_ be checked on entry/exit to a public method or property?

I'd extend that by saying I think it might be a good idea to split that in two, 
so that one can define entry and exit conditions, but I'm more interested in 
what everyone thinks of the general idea.

It could be very useful for the issues identified with std.random, but I'm not 
sure how it might impact on things like e.g. function properties.  For example, 
if this enforced entry condition checks for initialization and makes sure 
initialization takes place of it hasn't already, it would surely destroy the 
possibility of const for any struct/class method, no?

So, I thought I'd throw the idea out there so that others can suggest whether 
this is potentially useful or whether it's better/safer to hand-code such checks 
on a function-by-function basis.

Thanks & best wishes,

     -- Joe


More information about the Digitalmars-d mailing list