On 16.02.2011 11:03, Michael Engelhardt wrote:
Hi,
I just have started diving in D. Exploring the contract feature I
stumbled upon the fact that a class invariant does not apply to properties:
Welcome on board :)
Invariant gets called on every public method call (at begin & end if I'm not mistaken).
Now to properties, this is actually shouldn't be allowed:

 @property int hours;

@property is a annotation applied to functions (getter/setter), to allow 
calling it with omitted () and a natural assign syntax like this:

class Time {
private:
        int _hours;
public:
        //...
        @property int hours() {
                return _hours;
        }
        @property void hours(int newHours) {
                _hours = newHours;
        }
}

auto t = new Time();
t.hours = 5; // calls void hours(5)
assert(t.hours == 5); //calls int hours()

Now given that setter and getter are public methods they'd got the invariant 
called.


import std.stdio;

void main(string[] args) {
     Time t = new Time();
     t.hours = 24; // works; why?
     writeln("t.hours is ", t.hours);
     t.add(1); // triggers an assertion failure as expected
     writeln("t.hours is ", t.hours);
}

class Time {
     invariant() {
         assert( 0<= hours&&  hours<  13);
     }
     @property int hours;

     public void add(int hours) {
         this.hours += hours;
     }
}

compiled using Digital Mars DMD (2.051 on Ubuntu 10.10) is given the
following result:

t.hours is 24
core.exception.AssertError@invarprop(13): Assertion failure
----------------
./InVariantProperty() [0x8057ade]
./InVariantProperty() [0x804f7e6]
./InVariantProperty() [0x804cba3]
./InVariantProperty() [0x8049856]
./InVariantProperty() [0x804fa86]
./InVariantProperty() [0x8049869]
./InVariantProperty() [0x8049813]
./InVariantProperty() [0x804f9f2]
./InVariantProperty() [0x804f94c]
./InVariantProperty() [0x804fa36]
./InVariantProperty() [0x804f94c]
./InVariantProperty() [0x804f8f4]
/lib/libc.so.6(__libc_start_main+0xe7) [0xa5cce7]
./InVariantProperty() [0x8049721]

Should not a class invariant apply to properties, too?

Kind regards

Michael

--
Dmitry Olshansky

Reply via email to