Against enforce()

bearophile bearophileHUGS at lycos.com
Wed Mar 16 16:45:56 PDT 2011


enforce() seems the part of Phobos that I hate more. 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;
- It kills inlining (with the current DMD, and I don't think this problem will be fixed soon);
- I have seen it slow down code (probably mostly because of its not-inlining nature);
- 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.
- 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.

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.

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.

Bye,
bearophile


More information about the Digitalmars-d mailing list