Invariants are useless the way they are defined

Peter Williams pwil3058 at bigpond.net.au
Mon Aug 26 17:26:34 PDT 2013


On 25/08/13 22:16, deadalnix wrote:
> As they are defined now, invariant are plain useless. I find myself
> disabling them one by one in my code as soon as cases get outside simple
> trivia.
>
> The problem is that invariant are checked at the beginning/end on public
> function calls. As a consequence, it is impossible to use any public
> method in an invariant.
>
> For instance, just right now I did refactor a struct to use bitfields,
> in order to make it more compact. Now I have to remove the invariant as
> field access are now function calls.
>
> Another typical situation is when you want to assert certain properties
> in a class hierarchy, where calling virtual method is part of the
> invariant check.
>
> invariant should (and must to be useful) be inserted at callee point,
> when the callee isn't itself subject to invariant insertion, and around
> public memeber manipulation (when the manipulator isn't subject to
> invariant insertion).
>
> Any other pattern it doomed to create infinite recursion for non trivial
> invariant checks.

I just discovered another (surprising to me) shortcoming with the 
implementation of invariants: namely they don't get checked during the 
default initiation of a struct.  By default, I mean the initialization 
process that you get when you don't provide a this() method.

This probably doesn't matter in the grand scheme of things as I imagine 
an instance of the struct that breaks the invariant cant be used without 
triggering a check.  However, for me, it meant I had to use two 
statements in my unit tests (instead of one) to test the invariant. 
Also, the deferred triggering of the invariant could make debugging more 
difficult.

Peter


More information about the Digitalmars-d mailing list