[phobos] Pureness of enforce()

Jonathan M Davis jmdavisProg at gmx.com
Tue Nov 9 03:33:10 PST 2010


On Tuesday 09 November 2010 03:21:38 Lars Tandle Kyllingstad wrote:
> enforce(x) is basically a substitute for
> 
>   if (x) throw new Exception;
> 
> which doesn't violate the purity rules.  It is not possible to annotate
> enforce() with 'pure', however, because it takes a lazy parameter, which
> is just shorthand for a (possibly impure) delegate.
> 
> enforce() is used virtually everywhere in Phobos, and this means that a
> lot of functions that could otherwise be marked as pure, currently
> can't.
> 
> One example is std.conv.to(), which should definitely be pure.  (In
> fact, I tried marking it as such, which is what got me thinking about
> this in the first place.)
> 
> What to do?

The simplest is just to ditch it in favor of writing

if(x) throw new Exception;

or the equivalent. It really isn't much more code, it doesn't run any of the 
code necessary to create or throw the exception unless it has to, and it doesn't 
have to create a delegate. Granted, using enforce() is kind of nice, but if it 
can't be made pure, it's not worth it. All it really does is save you from 
putting the if and the throw in the statement. It's virtually identical 
otherwise.

Now, if we can find a way to make enforce() pure (probably with compiler help to 
deal with the lazy/delegate issue) that would be better, but I think that purity 
is worth _far_ more than the little bit of typing that enforce() saves you.

- Jonathan M Davis


More information about the phobos mailing list