Temporary suspension of disbelief (invariant)
Fawzi Mohamed
fawzi at gmx.ch
Wed Oct 27 07:33:58 PDT 2010
An issue I encountered in D1 with invariant is using delete: I have a
method that deletes the current object, and obviously then any
invariant would fail.
It would be nice to have a way to disable invariant in that case.
In D2, as delete is not allowed anymore (if I got it correctly) this
is not a problem.
Fawzi
On 27-ott-10, at 15:08, Stanislav Blinov wrote:
> 27.10.2010 4:00, bearophile wrote:
>> I have not asked this in the D.learn newsgroup because I think it
>> may be a bit interesting for other general people too.
>>
>> In D contract programming the invariant is not called before/after
>> private methods. I think that in some cases you may want to disable
>> the invariant even in some public methods. If your class/struct has
>> a public method that invalidates the state of the class instance,
>> and one public method that fixes the class instance state (I am
>> thinking about certain data structures where in a first phase you
>> may add many items, and then you ask the data structure to clean up
>> itself and become coherent. This may avoid some computations), I
>> have found this way to implement it:
> If I get this right, then it is by design that your class may have
> several general logical states: e.g. "initializing" and "coherent".
> Given this, I don't see why you'd want to disable invariant checks
> rather than modify those checks instead to validate current logical
> state. In fact, that "ghost" field simply serves as a flag for
> invariant showing which logical state it should enforce. The fact
> that states are 'logical', e.g. are different while represented by
> the same physical fields doesn't always rule them out as, uh, class
> states: you could as well have two separate inner classes that
> perform initialization and polishing, each with its own invariant.
> Then you could use those inner classes' private methods (without
> causing their invariant checks), but in main class' invariant
> perform an assert on them to ensure their state is valid.
>
> IMHO, proper invariants should be strict and act by the numbers at
> all times, otherwise there's little to no gain in using them at all.
More information about the Digitalmars-d
mailing list