An article about contract programming

FG home at fgda.pl
Tue Feb 5 09:42:40 PST 2013


On 2013-02-05 17:57, bearophile wrote:
> In D this code doesn't asserts:
>
>
> struct Foo {
>      int x = 200;
>      invariant() { assert(x > 100); }
> }
> void main() {
>      auto f = Foo(10);
> }
>
>
> Maybe it's good to introduce in D as in Ada a call to the invariant when the
> whole struct is assigned.


There's been a lot of talk about properties lately.
If it's only a constraint on Foo.x, assert could go in setter.
But how to force using a setter in Foo(10) initialization?

Now, suppose there's a group constraint:

     struct Dist {
         double x, y; double d;
         invariant() { assert((abs(x) + abs(y) <= d)); }
     }

Normally I'd throw in: bool isValid() {return (abs..... );}
But let's say we let the invariant do automated checking.

When should Dist's state validity be checked?
On completed initialization and then on every write?
(also check every read if, God forbid, Dist isn't pure?)
Function contracts were easy compared to this. :)



More information about the Digitalmars-d-announce mailing list