assert(obj) is a mystery
Jonathan M Davis
jmdavisProg at gmx.com
Wed Nov 9 09:35:46 PST 2011
On Wednesday, November 09, 2011 05:39 Alex Rønne Petersen wrote:
> On 09-11-2011 11:33, Jonathan M Davis wrote:
> > On Tuesday, November 08, 2011 21:51:46 Davidson Corry wrote:
> >> OK. Not addressing Alex's objections at all, it's not clear to me why
> >> anyone would *need* to test the invariant of an object.
> >
> > I wouldn't expect it to be something that you'd need to do very often.
> > However, if you give access to the member variables in your class or
> > struct - either directly or indirectly - allowing code outside the type
> > to modify that type's state, then the invariant can be violated. Now,
> > it's arguably bad design to allow such access when using an invariant
> > (if not in general), but it _is_ a case where the invariant can be
> > invalidated.
> >
> > - Jonathan M Davis
>
> I do think Good Practice (TM) dictates that you shouldn't expose
> something as mutable if mutating it violates the object's invariant.
> Instead, you should use a property with preconditions.
>
> In light of this, I can actually see why assert(obj) testing the
> invariant can seem very, very odd. (And I mean, nobody's going to write
> assert(this) or something like that...)
You _might_ write assert(this) if you've just called some private functions
and wanted to be sure that the invariant is still valid. Since the entire
module has access to private functions and variables, and since private
functions do _not_ trigger the invariant, it's quite possible for even a well-
written class or struct to get a messed up the variant if the module as a
whole has bugs. And even if private were restricted to the type, if you were
being thorough, you might want to run the invariant within your type after
running some private functions.
Still, I wouldn't expect assert(obj) or assert(this) to be common. The only
time that I've used it was in debugging when I was trying to figure out when
the invariant was invalidated within the type when there was a bug. So, I
definitely think that it's useful to be able to explicitly call the invariant,
but I'd also expect it to be quite rare.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list