Improve "Improve Contract Syntax" DIP 1009

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Nov 4 13:59:39 UTC 2017


On Saturday, November 04, 2017 13:02:45 Nick Treleaven via Digitalmars-d 
wrote:
> On Saturday, 4 November 2017 at 06:08:22 UTC, Jonathan M Davis
>
> wrote:
> > Heck, take a really simply one like sqrt. All you have to check
> > in the out contract is the return value. You have no idea what
> > was passed in. So, how would you write an out contract
> > verifying that you got the correct number? If you also had
> > access to the input, then you could do the reverse operation by
> > squaring the result to see if it matched the input (assuming of
> > course that floating point rounding errors don't make that not
> > work), but you don't have access to the input.
>
> I don't think I've ever written an out contract, so I am inclined
> to agree with you. However, there is a sqrt example for integers
> in the official docs, it does access its input:
>
> https://dlang.org/spec/contracts.html#pre_post_contracts
>
> long square_root(long x)
> in
> {
>      assert(x >= 0);
> }
> out (result)
> {
>      assert((result * result) <= x && (result+1) * (result+1) > x);
> }

I was sure that you couldn't do that, but apparently, I was wrong. However,
it does rely on the parameter not having been mutated. e.g.

void main()
{
    foo(42);
}

void foo(int x)
out
{
    import std.stdio;
    writeln(x);
}
body
{
    x = 7;
}

prints 7.

Being able to access the input of a function that doesn't mutate its input
does increase the usefulness of out contracts, but there are still plenty of
functions where you can't determine whether the output is correct just by
looking at the input without reimplementing the function in the out contract
to make sure that the results match (e.g. as I pointed out before, a hash
function isn't reversible, which means that you can't just verify the hash
for arbitrary input).

I'm very much of the opinion that proper unit tests pretty much eliminate
the need for out contracts.

- Jonathan M Davis



More information about the Digitalmars-d mailing list