Transitive Const in OO programming
Regan Heath
regan at netmail.co.nz
Wed Aug 8 01:34:29 PDT 2007
Alex Burton wrote:
> I am interested in what the best way to handle situations such as
> these in real D code.
>
> Transitive const combined with proper OO (no statics etc) means that
> no state can be preserved in const methods, given that everything a
> class refers to should be through a member or argument.
>
> Yes I know that I could make StateMachine not a state machine, but in
> reality there are state machines, and this one could be a mock one
> for testing.
>
> It comes down to whether all things that a class may refer to are
> necessarily part of that class for the purposes of const.
>
> In D 2.0 a call to a const method will not make any changes to
> anything that persists after the call returns unless it changes a
> mutable argument to that method. (ignoring statics) This would
> require state to be passed in to that method, which would require
> state to be passed into any const methods calling it, which breaks
> encapsulation.
>
> The code below fails to compile because
> StateMachineWrapper::getResult calls a non const member of
> StateMachine
>
> class StateMachine
> {
> int state;
> this()
> {
> state = 0;
> }
> void sendMessage()
> {
> state = 1;
> }
> const int getResult()
> {
> if (state == 1)
> {
> return 10;
> state = 0;
> }
> else
> throw new Exception("not in state to getResult");
> }
> };
>
> class StateMachineWrapper
> {
> StateMachine mMachine;
> this()
> {
> mMachine = new StateMachine;
> }
> const int getResult()
> {
> mMachine.sendMessage();
> return mMachine.getResult();
> }
> };
>
>
> void main()
> {
> const(StateMachineWrapper) wrapper = new StateMachineWrapper;
> int x = wrapper.getResult();
> }
StateMachine::getResult modifies state and cannot be 'const' either. In
this case I think you need a non-const StateMachine::reset to go back to
state = 0; It makes sense, especially if you want to call getResult
several times for example.
Why call StateMachine::sendMessage inside stateMachineWrapper::getResult?
Why does StateMachineWrapper::getResult have to be const?
It seems making StateMachineWrapper::getResult non-const solves the problem.
Regan
More information about the Digitalmars-d
mailing list