strange behavior of by-value function arguments in postcondition

FeepingCreature feepingcreature at gmail.com
Fri Sep 3 06:50:35 UTC 2021


On Friday, 3 September 2021 at 06:25:44 UTC, bauss wrote:
> On Thursday, 2 September 2021 at 13:33:34 UTC, Meta wrote:
>> On Wednesday, 1 September 2021 at 06:14:27 UTC, bauss wrote:
>>> Pre/post conditions _are_ assert statements tho. User 
>>> validation should be done using exceptions, not asserts.
>>
>> The fact that they are assert statements is an implementation 
>> detail. The point of pre/post conditions is to enforce that 
>> certain properties of the function hold, and assertions are 
>> just how the language happens to implement that.
>
> I would argue that they're there to enforce certain properties 
> of the function to hold true when testing, because you should 
> use exceptions otherwise!
>
> D's error handling is primarily exceptions and asserts should 
> never be used for error handling because they shouldn't be in 
> release builds and AFAIK release builds remove them.
>
> *snip*
>
> You'll end up with either silent errors that are hard to debug 
> OR you'll end up with tons of crashes with no clear indication.

Correct: asserts are not for input validation, they're for logic 
validation. This is why catching Errors is as close as D gets to 
"undefined behavior." (Compare the scary warnings on 
https://dlang.org/library/object/error.html )

> The solution here is actually to use exceptions if going by 
> idiomatic D:
> 
> void a(int x) in (x > 10) { if (x < 10) throw new 
> Exception(x.stringof ~ " is below 10."); writeln(x); }

Eh, I'd argue this shouldn't have an incondition. In my opinion, 
the compiler would be justified here in removing the exception, 
since you just told it, effectively, "x is always > 10". So the 
`x < 10` branch is "dead code".

But also, the `if (x < 10)` (really, `x <= 10`) test here is 
*why* you'd be justified in writing `in (i > 10)` later.


More information about the Digitalmars-d mailing list