Let's not make invariants const

Davidson Corry davidsoncorry at comcast.net
Fri Aug 3 13:17:16 PDT 2012


On 8/3/2012 12:40 PM, bearophile wrote:
> H. S. Teoh:
>
>> IMO, if you need to be changing stuff inside invariants, then you're
>> using it wrong. Invariants are intended to verify program logic, not
>> to do things like altering object state. The point is to be able to
>> compile with invariant code turned off, and still have the program
>> work exactly as before.
>
> I agree, modifying the state of the struct/class instance is not the job
> of contracts and invariants. D contract programming is already not tidy,
> so better to not make it even more messy.
>
> In a perfect world invariants and contracts should be pure too!

Absolutely. Invariant clauses (and contract clauses generally) must not
have side effects, lest the class behavior change depending upon whether
or not they are compiled into the build. Assigning a value within the
invariant clause is definitely a side effect.

It is the job of the *constructor* to establish the invariant state,
not of the invariant clause (which only *verifies* it).

The compiler *should* be catching a side effect in the invariant clause,
if it can do so statically.



More information about the Digitalmars-d mailing list