strange behavior of by-value function arguments in postcondition

deadalnix deadalnix at gmail.com
Fri Sep 3 08:34:11 UTC 2021


On Friday, 3 September 2021 at 05:47:32 UTC, FeepingCreature 
wrote:
> [lawyer analogy]
>
> The same thing applies here. It is legal to call `a.foo(5)` 
> because `a` is secretly a `B` object. But since you don't know 
> this, you are committing a reverse mistake of law: thinking 
> something is illegal, when it actually isn't, and doing it 
> anyway. So in a common law language like D this passes, but in 
> a civil law language, ie. with asserts at the callsite, it 
> would error.

The lawyer analogy doesn't quite apply.

in and out contract are about detecting errors. When the caller 
calls A.foo, it has no idea i is actually calling B.foo - Liskov 
substitution principle is at play here. It therefore doesn't know 
that it can call the function with the value it does. The fact 
that it does is therefore a logic error in the program. Either 
this code should use a B, and it shouldn't pass such parameter to 
the function. The goal of design by contract is to detect errors 
in the application, so here you go.

The fact that a contract fails is not a punishment, like it is in 
the law example. It is a blessing. It is your application telling 
you something is not right before you hit production (hopefully).


More information about the Digitalmars-d mailing list