On 03/16/2011 06:45 PM, bearophile wrote:
enforce() seems the part of Phobos that I hate more.

Yum, love the enforce.

Among its faults:
- It can't be used in weakly pure functions (because you can't use lazy 
arguments in pure functions), and not-purity is viral. Lot of Phobos can't be 
pure because of this, so even more user code can't be pure because of this;

So perhaps the language could be improved as enforce does not break purity.

- It kills inlining (with the current DMD, and I don't think this problem will 
be fixed soon);

Not a problem of enforce.

- I have seen it slow down code (probably mostly because of its not-inlining 
nature);

Not a problem of enforce.

- Where it is used it usually doesn't give a more meaningful exception like 
WrongArgumentException, etc. I don't want a deep hierarchy of one hundred 
standard exceptions, but I think some standard exceptions for the most common 
mistakes, like wrong arguments, etc, are better than a generic enforce(), 
especially for a standard library code that is meant to be written with care 
and to give better error messages/exceptions.

enforce helps such idioms, does not prevent them. From the docs:

===============
T enforce(T)(T value, lazy Throwable ex);

If value is nonzero, returns it. Otherwise, throws ex.
===============

- It doesn't allow functions to be nothrow. This is a fault, because D has 
Contract Programming, that is meant to be usable for nothrow functions too. D 
Contracts with asserts are the right tool.

enforce's specification specifies it throws. It would therefore be difficult for it to not throw. This complaint is non sequitur.

I see enforce() just as a temporary workaround for a problem of Phobos (that 
it's compiled in release mode, so its asserts are vanished) that risks to 
become a permanent part of Phobos.

enforce is a simple abstraction of the idiom "if (!condition) throw new Exception(args)". If that idiom were rare, then occurrences of enforce would be rare and therefore there would be little need to have enforce at all.

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.


Andrei

Reply via email to