Temporary suspension of disbelief (invariant)

Jonathan M Davis jmdavisProg at gmx.com
Tue Oct 26 17:47:03 PDT 2010


On Tuesday, October 26, 2010 17:25:20 Walter Bright wrote:
> bearophile wrote:
> > All this looks bug-prone, and surely hairy, but it looks potentially
> > useful. Is it a good idea to design a class that uses such temporary
> > suspension of the invariant?
> 
> An invariant that is not invariant is a meaningless attribute. It's like
> "logical constness" where classes claim to be const but aren't.

The only case that I'm aware of where it makes sense for a public function to 
not run the invariant is for opAssign() to not run it before it itself is run ( 
http://d.puremagic.com/issues/show_bug.cgi?id=5058 ), but that's because 
opAssign() is replacing the state of the object rather than updating it, so you 
don't care what it's state was beforehand. That's a special case though.

In the general case, it would overly complicate things to try and make an 
invariant not really be an invariant. If you really wanted to do that, you could 
use class variables which kept the state and made it so that the asserts in the 
invariant weren't run after a particular function call until another particular 
function call were made. But that strikes me as a colossally bad idea. Still, if 
you wanted such functionality, you _can_ get it, so I see no reason to 
complicate invariants just to make it easier to write what is likely bad code 
(or at least which is at a higher risk of being bad code).

- Jonathan M Davis


More information about the Digitalmars-d mailing list