Transitive Const in OO programming

Alex Burton alexibu at mac.com
Tue Aug 7 22:29:11 PDT 2007


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();	
}



More information about the Digitalmars-d mailing list