Let's not make invariants const

Alex Rønne Petersen alex at lycus.org
Fri Aug 3 13:41:26 PDT 2012


On 03-08-2012 22:17, Davidson Corry wrote:
> 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.

Of course... it was an example to demonstrate the current situation. It 
was by no means meant to be a sensible piece of code.

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

Yes, but sometimes it's useful to track and maintain state in an 
invariant in order to debug certain bugs that only manifest in systems 
programming languages like D. Unlike languages like C#, we can get e.g. 
memory corruption in D.

I find that in practice, enforcing const in invariants has not helped me 
in any way. It has forced me to fix countless errors upon a DMD upgrade, 
none of which indicated actual problems. That's what I got out of that. 
The likelihood of an invariant visibly altering program semantics due to 
side-effects is so low it's not worth the huge breakage IMO.

Further, I had to insert casts that cast away constness in some cases 
because the standard library just isn't const-friendly enough. We need 
to get our priorities straight.

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

Not if it breaks my 30.000 lines source base where not even a single one 
of the errors caught actual bugs. I refer to this as "waste of time".

-- 
Alex Rønne Petersen
alex at lycus.org
http://lycus.org


More information about the Digitalmars-d mailing list