Contract programming syntax

Michel Fortin michel.fortin at michelf.com
Wed Apr 8 18:06:11 PDT 2009


On 2009-04-08 10:46:19 -0400, bearophile <bearophileHUGS at lycos.com> said:

> 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);
> }

I believe the syntax should make the contracts part of the function 
signature, not part of the function body, because contracts are about 
expressing the function's interface. So I disagree with your proposed 
syntax which puts the contracts as part of the body.

I do agree however that reserving 'body' as a keyword is from time to 
time hindering. I'd certainly welcome a change if it allows removing 
'body' as a keyword. But not this one, because it puts the contract at 
the wrong place.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list