September 03, 2021

On Friday, 3 September 2021 at 06:53:40 UTC, bauss wrote:

>

On Friday, 3 September 2021 at 06:50:35 UTC, FeepingCreature

>

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

You haven't told the compiler that x will always be > 10. You have told the compiler that you expect it to always be above 10 but it might not be, say if the value came from user-input or a file somewhere in the call-chain. You have no way to guarantee that something always is something for the compiler, UNLESS the value can never come from a dynamic source.

You have a way to guarantee that something always is something - and you've already shown how: if (i <= 10). The if justifies the in.

If I expect i to be above 10 but it might not be, I write if and return an error. If I expect i to always be above 10, but want to sanity check or codify the assumption, I write assert.

I think when you write assert(i > 10) in any form, then i being <= 10 past that point should be illegal, ie. value range propagation should be able to rely on asserts having excluded parts of the range.

September 03, 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).

1 2 3
Next ›   Last »