Transitive const sucks

Alex Burton alexibu at mac.com
Wed Sep 12 15:52:12 PDT 2007


Walter Bright Wrote:

> Janice Caron wrote:
> > Even something as simple as this needs logical const
> > 
> > class MyMathClass
> > {
> >     invariant int multiply(int x, int y) /* logically const */
> >     {
> >         debug logfile.writeLine("multiply.called");
> >         return x * y;
> >     }
> > 
> >     debug private Stream logfile;
> > }
> > 
> > You can't tell me that's not a real world need.
> 
> You can:
> 
> 1. make logfile a static member.
Unacceptable - statics are bad as anyone writing good OO code with tests can tell you.

> 2. not use invariant on the multiply. After all, if it isn't actually 
> invariant, the invariant declaration wouldn't have any more meaning than 
> the comment you put on it.

It is far more than a comment. This class may be passed all through an application and as long as only const references to MyMathClass are we can be sure that all this code is not calling any other non const methods, only the ones marked as invariant which don't change the state of MyMathClass.
Without transitive const, the logfile might be changed, but who cares, it's not part of the MyMathClass and no contract was made about modfying objects other than the current instance of MyMathClass.

Basically I think you are trying really hard to kill many birds with one stone: thread safety checkable by compiler, const system for optimisation and lastly const system that is actually usable by programmer.
This has never been done before and I commend you for working on it.

I obviously don't know as much about compilers as you but, there seem to be limitations that you dont seem to be able to communicate to us about why you need transitive const.

In the above example what prevents the compiler from changing any calls to multiply to:
myMathClass.multiply(3,3);
debug myMathClass.logfile.writeLine("multiply.called");

So now constness of the actual multiply call are preserved, and we can log the data too.

Is it because the compiler is unable to see in side other functions unless they are templates - like c++ ?




More information about the Digitalmars-d mailing list