class invariants and property declarations

Michael Engelhardt me at mindcrime-ilab.de
Wed Feb 16 00:03:40 PST 2011


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:

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 at 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


More information about the Digitalmars-d-learn mailing list