How does D improve design practices over C++?
Tony
tonytech08 at gmail.com
Fri Nov 7 13:51:21 PST 2008
"Janderson" <ask at me.com> wrote in message
news:gf0e9n$31ff$1 at digitalmars.com...
> 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
I need a large list of examples where invariants were used because I just
don't see many opportunities to use them in my own codebase. Also, they seem
mainly useful as a development aid rather than as production code (similar
to turning off assertions in release code).
Tony
More information about the Digitalmars-d
mailing list