On Saturday, 27 January 2018 at 16:19:30 UTC, Jonathan M Davis wrote:
On Saturday, January 27, 2018 14:59:50 kdevel via Digitalmars-d-learn wrote:
>>> https://github.com/dlang/phobos/blob/master/std/exception.d
>>
>> "Use $(D assert) in contracts." is still in there.
>
> What's wrong with that? What documentation is trying to say > is "do not use enforce in contracts; use assert in > contracts" and that's exactly the idea.

I can't see a problem which would be solved by following this advice. It distracts the reader (me) from gettin his (my) work done. If I compile not for release both, enforce and assert, are in effect. If I compile for release both, enforce and assert, are disabled. So by replacing enforce with assert I gain nothing.

No, enforce is _not_ disabled with -release. e.g.

That's not my point.

void foo(int i)
{
    enforce(i > 42);
}

void main()
{
    foo(0);
}

This is a different case.

will throw an exception even when you compile with -release. The problem is that you're using enforce inside a contract instead of inside the function's body.

This is not a problem, because this is perfectly legal. The problem is the wording of this phrase on the docs:

| Also, do not use enforce inside of contracts (i.e. inside of in and out blocks | and invariants), because they will be compiled out when compiling with
| -release. Use assert in contracts.

Using assert *IN* contracts in -release mode is equally pointless.

Contracts are specifically for asserting pre and post conditions. It is expected that they only be used for assertions or for code which is going to be run in preparation for running an assertion. They are _not_ for code which is intended to be part of the final program, and they are compiled out with -release, just like assertions are compiled out elsewhere in the code. As such, any code in a contract - be it an assertion, a call to enforce, or any arbitarily complex piece of code - will not be in the final program.

Then please explain the meaning of the sentence

     Use assert in contracts.

in this context:

| Also, do not use enforce inside of contracts (i.e. inside of in and out blocks | and invariants), because they will be compiled out when compiling with
| -release. Use assert in contracts.

to me. IMHO this advice is pointless.

Anything that you want in your final program should not be in a contract. If you want to use exceptions - be it with enforce or with an if statement and explicitly throwing - then don't put them in any contracts. They _will_ get compiled out. As such, it makes no sense to use enforce in a contract. It should go in the function body.

Then please explain to me, in which respect the advice to "Use assert[s] in contracs" makes sense if the contracts are to be compiled out. I don't get it.

Reply via email to