Against enforce()

Adam D. Ruppe destructionator at gmail.com
Wed Mar 16 16:59:40 PDT 2011


bearophile wrote:
> - 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.

assert and enforce cover a completely different problem, and aren't
interchangeable.

assert catches programming errors. If an assert fails, it's a bug
that the programmer should fix.

enforce, on the other hand, catches runtime errors that aren't
the programmer's fault. Then *have* to be handled to be correct, so
being nothrow is out of the question. The function is *not*
guaranteed to succeed at runtime.


Look at the way enforce is generally used inside Phobos.

enforce(fp = fopen("file", "r"));

That is something that could fail at no fault of the programmer.
It's an exception, not an assert.


By far, the majority of enforces in Phobos are of this variety.
They cannot possibly be made into contracts, and even if they
could, that would be wrong.



That said, I tentatively agree that enforce may be bad right now
because of the other things you said (except the meaningful
exception. enforce does that with an optional argument.)

enforce is just a lazy way to write if(xxxxx) throw T(msg);

It is elegant, it is beautiful, but if the practical problems
aren't fixed, it might be right to avoid it anyway.

But it'd have to be replaced with if/throw, not assert.


More information about the Digitalmars-d mailing list