Contract programming syntax

bearophile bearophileHUGS at lycos.com
Wed Apr 8 07:46:19 PDT 2009


I like contract programming, it helps me avoid bugs. This is an example from the docs:

long squareRoot(long x)
    in {
        assert(x >= 0);
    }

    out (result) {
        assert((result * result) <= x && (result+1) * (result+1) >= x);
    }

    body {
        return cast(long)std.math.sqrt(cast(real)x);
    }


But isn't a syntax like the following better? To me it looks more logic, because in{} and out(){} are part of the function, and there's no need of a special syntax for the body (and the 'body' keyword):

long squareRoot(long x) {
    in {
        assert(x >= 0);
    }

    out (result) {
        assert((result * result) <= x && (result+1) * (result+1) >= x);
    }

    return cast(long)std.math.sqrt(cast(real)x);
}

Bye,
bearophile



More information about the Digitalmars-d mailing list