How does D improve design practices over C++?

Janderson ask at me.com
Thu Nov 6 19:56:36 PST 2008


Tony wrote:

>> long square_root(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);
>>     }
> 
> Or if one wanted something like that in C++:
> 
> class MyInvariant
> {
>     MyInvariant(long& x)
>     {
>         // do a check on entry
>     }
> 
>     ~MyInvariant()
>     {
>         // do a check on exit
>     }
> };
> 

You should know that the syntax I presented above is not an invariant in 
D (that's a contractual check).  An invariant check in D looks like this:

class Foo
{
     public void f() { }
     private void g() { }

     invariant()
     {
	//Checked for both f and g
     }
}

The invariant example was what I originally said in my first reply was a 
lot of extra work in C++.  Note I used invariant checks a lot in C++ and 
D's invariant checks are far better.  You might want to read though the 
D documentation so that what I've said makes more sense.  You seem to 
reply only half reading what I've said (case-in-point above).

The documentation can be found here:

http://www.digitalmars.com/d/2.0/lex.html

and here for 1.0

http://www.digitalmars.com/d/1.0/lex.html

-Joel



More information about the Digitalmars-d mailing list