verifying my robot manipulation

In this post I'm going to wrap up this second robocode series by verifying that my new design works the way I want it to and hopefully showing that all this work has paid off.

To review, here's a brief description of my design:

  • the run method is called on my robot by robocode
  • my robot first retrieves a robot engine from a service locator and passes itself to the engine
  • the run infinite loops begins and there is only one thing to do each loop: the robot asks the robot engine to ensure the world state is up to date
  • the robot engine processes any pending world state updates that have been stored by events
  • if there are no updates, this process finishes until the next loop
  • otherwise, it pushes the updated world state to each context translator
  • the context translators convert the world state into a new state for that bounded context
  • the observable situation (using rx observables) is updated
  • any observers with subscriptions that meet the new state come into effect

I have two observers at present, one in the decision context to write statistics out for my acceptance test, showing that the robot was not disabled at the start of the battle (and there are no terminal exceptions as a result of new code).
The second is a manipulation observer that looks for enemies when we have no focus.

As I cannot debug my robot through visual studio, I have littered areas of my code with WriteDebugMessage statements for this exercise so I can watch the turn snapshot window.

So to begin, here's the battlefield:

Verifying1

At the start of the battle, there's not much activity yet on turn 0 as expected:

verifying2

But moving onto turn 1 and there's a lot going on:

verifying3

The OnStatus event has been called and the robot is about to publish the world state update to the robot engine as a pending update.
The world state update is processed by the run loop and the robot engine starts pushing the state update to the bounded contexts.

The decision context translator gets the first update and updates the decision state keeper. This publishes the decision state via an observable situation. My only observer in this context waits for turn fifty, so it is not yet called.

The manipulation context translator now gets an update and this flows through to the manipulation state keeper. Again, the observable situation for this bounded context is updated and we do have an observer subscribing to when there is no focus (and there will always be no focus at present).
This "we have no focus observer" is responsible for pushing a command to the robot via the ImARobot interface to look for enemies.

Turn two occurs and we have some activity! The robot has issued a TurnRadarRight(360) and this radar scan has begun.

verifying4

For the next few turns, the turn snapshot window is a little quieter as the blocking call (because this is a standard robot) takes effect.
What is interesting is that as the OnStatus call still takes place, the world state updates are stored in the robot engine:

verifying5

So all of these stay as pending updates in the robot engine until the robot run loops kicks in again and we can begin processing again. This is exactly what the design called for and I'm very pleased with that.

When the radar scan is over, it all kicks in again, on turn ten:

verifying6

I still have no focus so the manipulation observer once again issues the look for enemies command:

verifying7

So it all looks to be working the way I wanted it to. I have a domain driven design model that is completely independent from the robocode library using the adapter robot to act as the anti corruption layer.
I have a command being pushed to the robot and my efforts seem to have paid off.

If you have been following this series, please let me know what you think about my experiments.

My next robocode series will look at making the robot do some more interesting things and expanding upon this design.

Posted at at 8:17 AM on Thursday, October 28, 2010 by Posted by Justin Davies | 1 comments Links to this post   | Filed under:

manipulating my robocode robot

I'm at a stage in my robocode implementation that I can begin to write some more observations and begin manipulating my robot. In this post I'll be:

  • creating a new observer for when there is no focus
  • issuing instructions to the robot to look for enemies
  • investigating and resolving a stackoverflow exception!
  • finally watching my robot be manipulated for the first time in my domain driven design code. At last!

The observer I'm wanting to begin with is the one that will ensure the robot looks for enemies and will effectively stop the robot being dormant. I therefore want to check if we are focused on anything and if we are not, I want to issue instructions to the robot engine. Here's the specification for this observer:

    [Subject(typeof(WeHaveNoFocusObserver))]
    public class when_there_is_no_current_focus
    {
        Establish context = () =>
        {
            manipulationState = new ManipulationState { WeAreFocusedOnSomething = false };
            manipulationStateEvent = MockRepository.GenerateStub<IEvent<ManipulationState>>();
            manipulationStateEvent.Stub(s => s.EventArgs).Return(manipulationState);
            manipulationStateObservable = Observable.Return(manipulationStateEvent);
            
            robotEngine = MockRepository.GenerateStub<ImARobotEngine>();
            robotEngine.Stub(e => e.IssueInstructionsToRobot(null))
                       .IgnoreArguments().Do(RecordInstruction);

            weHaveNoFocusObserver = new WeHaveNoFocusObserver(robotEngine);
        };

        Because of = () => weHaveNoFocusObserver.Observe(manipulationStateObservable);

        It should_subscribe_to_the_observable_and_recognise_that_we_have_no_focus = () =>
            weHaveNoFocusObserver.RecognisedThatWeHaveNoFocus.ShouldBeTrue();

        It should_issue_instructions_for_the_robot_engine_to_look_for_enemies = () =>
            ShouldHaveIssuedInstruction(x => x.LookForEnemies());

        static Action<Action<ImARobot>> RecordInstruction = i => 
                                                  instructionSentToRobotEngine = i;

        static void ShouldHaveIssuedInstruction(Action<ImARobot> expectedInstruction)
        {
            var robot = MockRepository.GenerateStub<ImARobot>();
            if (instructionSentToRobotEngine != null)
                instructionSentToRobotEngine(robot);
            robot.AssertWasCalled(expectedInstruction);
        }

        static ManipulationState manipulationState;
        protected static IEvent<ManipulationState> manipulationStateEvent;
        protected static IObservable<IEvent<ManipulationState>> manipulationStateObservable;        
        static WeHaveNoFocusObserver weHaveNoFocusObserver;
        static ImARobotEngine robotEngine;
        static Action<ImARobot> instructionSentToRobotEngine;
    }

This specification is very similar to the original start of the battle observer (if you have been following the whole series) which is now removed and replaced by this new manipulation state observer.

Essentially the specification is setting up some manipulation state which shows there is currently nothing in focus and providing this via an observable when it is told to observe.
Then, a robot engine is stubbed and it is set to record any instruction action of type Action<ImARobot> that is sent to it.

Finally I'm then taking the recorded action and manipulating a newly stubbed robot - this way I can determine what the action delegate contains and assert that it was the expected instruction of LookForEnemies().

Here's the implementation to make this pass:

    public class WeHaveNoFocusObserver : IObserveToManipulate
    {
        ImARobotEngine robotEngine;

        public WeHaveNoFocusObserver(ImARobotEngine robotEngine)
        {
            this.robotEngine = robotEngine;
        }

        public void Observe(IObservable<IEvent<ManipulationState>> situation)
        {
            situation.Where(s => s.EventArgs.WeAreFocusedOnSomething == false)
                .Subscribe(s =>
                   {
                        RecognisedThatWeHaveNoFocus = true;
                        robotEngine.IssueInstructionsToRobot(r => r.LookForEnemies());
                   });
        }

        public bool RecognisedThatWeHaveNoFocus { get; private set; }
    }

It is now looking very simple for me to add behaviour into my robocode code - the above code now subscribes to when there is no focus and looks for enemies. Here's the code for that LookForEnemies() call that was built in a previous post, and only part of the robot is shown here :

    public class SlayerRobot : Robot, ImARobot
    { 
        public void LookForEnemies()
        {
            TurnRadarRight(360);
        }

    }

This all looks great, but when I run through robocode it completely crashes on me!
A stackoverflow exception is killing the application.

After a little digging it is because I have a circular dependency in the constructor of the ManipulationStateKeeper.
When a robot engine is resolved from the IOC container, it creates a manipulation state keeper and the constructor of this is then asking the service locator to resolve a robot engine; this then creates another manipulation state keeper and so on until it crashes.

The solution is to ensure the service locator caches the resolved robot engine and to then change the ManipulationStateKeeper so that the process of passing the robot engine to the manipulation observers occurs a little later:

    public class ManipulationStateKeeper : StateKeeper<ManipulationState, IObserveToManipulate>
    {
        public ManipulationStateKeeper(IEnumerable<IObserveToManipulate> observers) : 
                                                                               base(observers)
        {
        }

        protected override ManipulationState EnsureThatStateHasBeenCreated()
        {
            return new ManipulationState();
        }

        protected override IObservable<IEvent<ManipulationState>> 
                                                EnsureThatTheObservableHasBeenCreated()
        {
            EnsureThatObserversAreGivenTheRobotEngine();

            return Observable.FromEvent<ManipulationState>(
                ev => this.StateHasUpdated += ev,
                ev => this.StateHasUpdated -= ev);
        }

        void EnsureThatObserversAreGivenTheRobotEngine()
        {
            var robotEngine = ServiceLocator.ObtainThePreviouslyRequestedRobotEngine();
            foreach (var observer in observers)
            {
                observer.UseTheRobotEngine(robotEngine);
            }
        }
    }

Now when I run my code in a battle, my robot is finally manipulated and scans for enemies!

MyRobotIsManipulated

Posted at at 7:29 PM on Tuesday, October 26, 2010 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , ,

making manipulation possible for my robocode implementation

More robocode again and I'm attempting to introduce an observer that will ensure my robot looks for enemies at the start of the battle, replacing the one I have discarded since I went down the domain driven route. At the moment, my robot is inanimate, so it is essential I get some manipulation in place.

Here's what I look at in this post:

  • the creation of a new manipulation state keeper using the generic state keeper
  • implement the context translator to turn the world state into the manipulation state
  • look at obtaining the robot engine from the service locator
  • pass this robot engine to all manipulation observers

So I start with the creation of a new manipulation state keeper and using the generic state keeper from my last post, it should be very easy to manage manipulation state and the observable situation. I'll start with a specification for my manipulation state keeper in the new manipulation namespace:

namespace Specifications.Model.Manipulation
{
    [Subject(typeof(ManipulationStateKeeper))]
    public class when_provided_with_a_state_update
    {
        Establish context = () =>
        {
            manipulationObserver = MockRepository.GenerateStub<IObserverToManipulate>();
            manipulationStateKeeper = new ManipulationStateKeeper(
                                 new List<IObserverToManipulate> {manipulationObserver});

            manipulationStateKeeper.Situation.Subscribe(s =>
                {
                    observedManipulationState = s.EventArgs;
                });

            manipulationStateUpdate = s => s.WeAreFocusedOnAnything = true;
        };

        Because of = () => 
            manipulationStateKeeper.UpdateState(manipulationStateUpdate);

        It should_update_the_situation_observable = () => 
            observedManipulationState.ShouldNotBeNull();

        It should_have_the_correct_manipulation_state_after_the_update = () =>
            observedManipulationState.WeAreFocusedOnAnything.ShouldBeTrue();

        static IObserverToManipulate manipulationObserver;
        static ManipulationStateKeeper manipulationStateKeeper;
        static ManipulationState observedManipulationState;
        static Action<ManipulationState> manipulationStateUpdate;
    }
}

Implementing this is very easy now that most of the behaviour is in the base generic state keeper:

    public class ManipulationStateKeeper : StateKeeper<ManipulationState, IObserverToManipulate>
    {
        public ManipulationStateKeeper(IEnumerable<IObserverToManipulate> observers) : 
                                                                      base(observers)
        {
        }

        protected override ManipulationState EnsureThatStateHasBeenCreated()
        {
            return new ManipulationState();
        }

        protected override IObservable<IEvent<ManipulationState>> 
                                         EnsureThatTheObservableHasBeenCreated()
        {
            return Observable.FromEvent<ManipulationState>(
                ev => this.StateHasUpdated += ev,
                ev => this.StateHasUpdated -= ev);
        }
    }

The next thing to write is my context translator - this will push the state from the world state into my manipulation state. At the moment I have no state to push, so this is going to be the bare bones implementation for the time being:

    [Subject(typeof(ManipulationContextTranslator))]
    public class when_publishing_a_state_change
    {
        Establish context = () =>
        {
            worldState = MockRepository.GenerateStub<IWorldState>();
            manipulationStateUpdater = MockRepository.GenerateStub<IUpdateManipulationState>();
            manipulationContextTranslator = 
                               new ManipulationContextTranslator(manipulationStateUpdater);
        };

        Because of = () => manipulationContextTranslator.PublishAStateChange(worldState);

        It should_update_state_via_the_manipulation_state_updater = () =>
            manipulationStateUpdater.AssertWasCalled(m => 
                                   m.UpdateState(Arg<Action<ManipulationState>>.Is.NotNull));

        static ManipulationContextTranslator manipulationContextTranslator;
        static IUpdateState<ManipulationState> manipulationStateUpdater;
        static IWorldState worldState;
    }

This specification ensures that the manipulation state keeper is sent an action to update the manipulation state. This will then fire the event and thus the situation observable. Here's the implementation for now to meet this specification:

    public class ManipulationContextTranslator : IContextTranslator
    {
        IUpdateState<ManipulationState> manipulationStateUpdater;

        public ManipulationContextTranslator(IUpdateState<ManipulationState> 
                                                              manipulationStateUpdater)
        {
            this.manipulationStateUpdater = manipulationStateUpdater;
        }

        public void PublishAStateChange(IWorldState worldState)
        {
            manipulationStateUpdater.UpdateState(m => { });
        }
    }

Next, I want to revisit the state keeper - when it is created, I want it to to have a copy of the robot engine so that it can pass it to all the manipulation observers. They will then be able to issue manipulation commands appropriately.

Unfortunately, if it comes in on the constructor then Autofac gives ma a circular dependency problem as the robot engine is at the root of all my dependency resolution already.
So how should I provide this via the service locator? This is currently an instance class that the robot itself creates and uses to resolve the engine and thus hook into IOC and the resolving of all dependencies when robocode activates the robot.
I'll have to have a static that returns the robot engine and though this is not ideal, it will serve my needs for the time being until I come up with a better plan.

There's one problem though, how do I test that the state keeper obtains the robot engine via a new static method or member?  Using delegates, I should be able to sort this out. So first, let me go back to the service locator specs and add a second specification:

    public class when_told_to_provide_a_robot_engine
    {
        Establish context = () => serviceLocator = new ServiceLocator();

        Because of = () => robotEngine = serviceLocator.ProvideRobotEngine();

        It should_return_a_valid_robot_engine = () => 
            robotEngine.ShouldNotBeNull();

        It should_ensure_we_are_able_to_obtain_the_same_robot_engine_by_another_route = () =>
            ServiceLocator.ObtainThePreviouslyRequestedRobotEngine().ShouldEqual(robotEngine);

        static ILocateServices serviceLocator;
        static ImARobotEngine robotEngine;
    }

I have a new specification here that ensures that when a robot engine is obtained statically from the service, that it is the same robot engine instance that the robot obtains from the instance method ProvideRobotEngine().
Here's the implementation for that:

    public class ServiceLocator : ILocateServices
    {
        static IContainer _container;

        public ServiceLocator()
        {
            RegisterEverything();
        }

        void RegisterEverything()
        {
            var builder = new ContainerBuilder();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AsImplementedInterfaces();

            builder.RegisterType<RobotEngine>().As<ImARobotEngine>().SingleInstance();

            _container = builder.Build();
        }

        public ImARobotEngine ProvideRobotEngine()
        {
            return _container.Resolve<ImARobotEngine>();
        }

        public static Func<ImARobotEngine> ObtainThePreviouslyRequestedRobotEngine = 
                                  () => _container.Resolve<ImARobotEngine>(); 
    }

I now have the robot engine registered as a single instance in Autofac and the delegate at the foot of the class ensures the same robot engine can be provided. I can also use this as a hook for testing the manipulation state keeper:

    [Subject(typeof(ManipulationStateKeeper))]
    public class when_created
    {
        Establish context = () =>
        {
            firstManipulationObserver = MockRepository.GenerateStub<IObserveToManipulate>();
            secondManipulationObserver = MockRepository.GenerateStub<IObserveToManipulate>();
            robotEngine = MockRepository.GenerateStub<ImARobotEngine>();
            ServiceLocator.ObtainThePreviouslyRequestedRobotEngine = () => robotEngine;
        };

        Because of = () => manipulationStateKeeper =
                              new ManipulationStateKeeper(new List<IObserveToManipulate> 
                                { firstManipulationObserver, secondManipulationObserver });

        It should_pass_the_robot_engine_from_the_service_locator_to_the_first_observer =
      () => firstManipulationObserver.AssertWasCalled(o => o.UseTheRobotEngine(robotEngine));

        It should_pass_the_robot_engine_from_the_service_locator_to_the_second_observer =
      () => secondManipulationObserver.AssertWasCalled(o => o.UseTheRobotEngine(robotEngine));

        static ManipulationStateKeeper manipulationStateKeeper;
        static IObserveToManipulate firstManipulationObserver;
        static IObserveToManipulate secondManipulationObserver;
        static ImARobotEngine robotEngine;
    }

In the context I am replacing the delegate on the service locator so that it returns a stubbed robot engine.
Then I can observe that is passes this robot engine to each observer.
Here's the result:

    public class ManipulationStateKeeper : StateKeeper<ManipulationState, IObserveToManipulate>
    {
        public ManipulationStateKeeper(IEnumerable<IObserveToManipulate> observers) 
                                                                          : base(observers)
        {
            var robotEngine = ServiceLocator.ObtainThePreviouslyRequestedRobotEngine();
            foreach (var observer in observers)
            {
                observer.UseTheRobotEngine(robotEngine);
            }
        }

        protected override ManipulationState EnsureThatStateHasBeenCreated()
        {
            return new ManipulationState();
        }

        protected override IObservable<IEvent<ManipulationState>> 
                                               EnsureThatTheObservableHasBeenCreated()
        {
            return Observable.FromEvent<ManipulationState>(
                ev => this.StateHasUpdated += ev,
                ev => this.StateHasUpdated -= ev);
        }
    }

    public interface IObserveToManipulate : IContextObserver<ManipulationState>
    {
        void UseTheRobotEngine(ImARobotEngine robotEngine);
    }

This hasn't been an ideal situation as I now have a public static delegate member on my service locator and this abstraction is now leaking, but I spent a long time trying to find a solution to the circular dependency issue, and this is the only real alternative I have at present.
In my next post I'll finally be writing the observer and making some commands to my robot.

Posted at at 8:22 AM on Monday, October 18, 2010 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , ,

the generic state keeper and the observer

In my previous post I explored the state keepers for my robocode implementation and had a working generic state keeper.
However, there was a problem that this new design created and I'm going to discuss this by looking at my existing observer. Here's the original code for that observer before the change:

namespace TeamSlayer.Model.Decision
{
    public interface IObserveToMakeDecisions
    {
        void Observe(IKeepDecisionState decisionStateKeeper);
    }

    public class BattleReachedAReasonableTurnObserver : IObserveToMakeDecisions
    {
        readonly IManageStatistics statisticsManager;

        public BattleReachedAReasonableTurnObserver(IManageStatistics statisticsManager)
        {
            this.statisticsManager = statisticsManager;
        }

    public void Observe(IKeepDecisionState decisionStateKeeper)
        {
            decisionStateKeeper.Situation.Where(s => s.EventArgs.TheNumberOfTurnsSoFar == 50)
                       .Subscribe(s =>
                       {
                           ReachedTurnFifty = true;
                           statisticsManager.WriteStatistics(ReachedTurnFifty);
                       });
        }

        public bool ReachedTurnFifty { get; private set; }
    }
}

To recap, this code is in the decision bounded context and namespace and the observer is presented with the decision state keeper when asked to observe; the observer then subscribes to the observable situation.

Here's the new code once the generic state keeper is in place:

using TeamSlayer.Model.World;

namespace TeamSlayer.Model.Decision
{
    public interface IObserveToMakeDecisions : IContextObserver<DecisionState>
    {
    }

    public class BattleReachedAReasonableTurnObserver : IObserveToMakeDecisions
    {
        readonly IManageStatistics statisticsManager;

        public BattleReachedAReasonableTurnObserver(IManageStatistics statisticsManager)
        {
            this.statisticsManager = statisticsManager;
        }

        public void Observe(IKeepState<DecisionState> decisionStateKeeper)
        {
            decisionStateKeeper.Situation.Where(s => s.EventArgs.TheNumberOfTurnsSoFar == 50)
                .Subscribe(s =>
                               {
                                   ReachedTurnFifty = true;
                                   statisticsManager.WriteStatistics(ReachedTurnFifty);
                               });
        }

        public bool ReachedTurnFifty { get; private set; }
    }
}

The decision observer interface now has no implementation and simply declares the state type for the context observer. This is great as it effectively acts as a translator, abstracting the world namespace away from anything in the decision context - I'm very happy with this.

The observer is now presented with a generic state keeper via the IKeepState<State> interface and this I do not like - the using statement shown at the top clearly shows I'm violating my domain driven design concept of a bounded context that I originally wanted.
I now have to think about how to address this and after some tinkering I come to the conclusion that the Situation observable is effectively typed by the decision state keeper, so I should be able to use this.

To get this to work though, I have to change the generic state keeper around - I'm going to omit the specifications for brevity once again as this takes a bit of explaining. First, I change the contract of the context observer to use the observable situation instead of the state keeper itself and replace the Situation property in the observer call in place of sending "this" into the method call:

namespace TeamSlayer.Model.World
{
    public interface IContextObserver<State>
    {
        void Observe(IObservable<IEvent<State>> situation);
    }

    public abstract class StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
        where Observer : IContextObserver<State>
        where State : EventArgs
    {
       // rest of the class left out for this illustration

       protected abstract IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();

        public IObservable<IEvent<State>> Situation
        {
            get
            {
                return situation ?? ( situation = EnsureThatTheObservableHasBeenCreated());
            }
        }

        public StateKeeper(IEnumerable<Observer> observers)
        {
            foreach (var observer in observers)
            {
                observer.Observe(Situation);
            }
        }
    }
}

I've highlighted a problem in red that this change presents - my situation property calls out to a derived implementation of this class through an abstract method and this is not a good situation. This is the same problem I outlined in my last post where we would be calling into a derived class whilst in the base constructor and we will not be able to guarantee the derived class is initialised properly.

So to fix this, I'm going to have to pull the observer registration to when the update change is pushed to the state keeper:

    public abstract class StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
        where Observer : IContextObserver<State>
        where State : EventArgs
    {
        IEnumerable<Observer> observers;
        IObservable<IEvent<State>> situation;
        bool weHaveNotYetShownObserversOurSituation = true;
        State internalState;

        State InternalState
        {
            get
            {
                return internalState ?? (internalState = EnsureThatStateHasBeenCreated() );
            }
        }

        protected abstract State EnsureThatStateHasBeenCreated();

        protected abstract IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();

        protected event EventHandler<State> StateHasUpdated;

        public void UpdateState(Action<State> stateUpdate)
        {
            if (weHaveNotYetShownObserversOurSituation)
            {
                EnsureThatObserversHaveRegisteredObservations();
                weHaveNotYetShownObserversOurSituation = false;
            }

            stateUpdate(InternalState);
            StateHasUpdated(this, InternalState);
        }

        void EnsureThatObserversHaveRegisteredObservations()
        {
            foreach (var observer in observers)
            {
                observer.Observe(Situation);
            }
        }

        public IObservable<IEvent<State>> Situation 
        { 
            get
            {
                if (situation == null)
                    situation = EnsureThatTheObservableHasBeenCreated();

                return situation;
            } 
        }

        public StateKeeper(IEnumerable<Observer> observers)
        {
            this.observers = observers;
        }
    }

In the constructor, I'm simply storing the observers and when the update state happens I check if I have asked the observers to observe and if that has not already taken place, I do so.

The implementation of the original observer that had the bounded context leak issue now changes to:

namespace TeamSlayer.Model.World
{
    public interface IContextObserver<State>
    {
        void Observe(IObservable<IEvent<State>> situation);
    }
}

namespace TeamSlayer.Model.Decision
{
    public class BattleReachedAReasonableTurnObserver : IObserveToMakeDecisions
    {
        readonly IManageStatistics statisticsManager;

        public BattleReachedAReasonableTurnObserver(IManageStatistics statisticsManager)
        {
            this.statisticsManager = statisticsManager;
        }

        public void Observe(IObservable<IEvent<DecisionState>> situation)
        {
            situation.Where(s => s.EventArgs.TheNumberOfTurnsSoFar == 50)
                .Subscribe(s =>
                               {
                                   ReachedTurnFifty = true;
                                   statisticsManager.WriteStatistics(ReachedTurnFifty);
                               });
        }

        public bool ReachedTurnFifty { get; private set; }
    }
}

I've now removed the using statement to the world context and this observer is now isolated in the decision context once again.

What is interesting is that as this observer is now passed the situation observable, typed to the state of this bounded context, this in fact makes much more sense than the previous implementation. Once again, a code change has moved me towards deeper insight about my code and cleared this area up - the bounded context concept has made me think about isolation in a new way.

Posted at at 7:41 AM on Monday, October 11, 2010 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,

revisiting robocode state with generics

In my robocode series I've reworked my code into bounded contexts and so far I have a robot that does not get disabled in battle and can report that it reached turn fifty.
However, it still does very little and does not move or scan for enemies.
I have an additional acceptance test that ensures I win against the sitting duck robot so my next piece of work is to get this test to pass. I think this is going to need some more decision context work and the introduction of some new bounded contexts.

Before I reworked my code to use domain driven design concepts, I had a simple observer that at the start of the battle issued instructions for the robot to look for enemies. I want to re-implement this in one of my contexts and I decide that the manipulation context is the best location for this as I will be manipulating the robot with this observation.

I start to write my specifications for the ManipulationContextTranslator and this suggests I require a ManipulationState and thus something to keep and update this state, for example ManipulationStateKeeper.

When beginning the specs for this, it is clear that the code is almost exactly the same as the previous DecisionStateKeeper so I decide to stop and instead see if I can make any of this code reusable, using the existing DecisionStateKeeper as the blueprint and running its unit test as I go.

Here's what I originally had in the DecisionStateKeeper as a reminder:

    public class DecisionStateKeeper : IKeepDecisionState, IUpdateDecisionState
    {
        DecisionState internalDecisionState;

        public DecisionStateKeeper(IEnumerable<IObserveToMakeDecisions> 
decisionMakingObservers) { CreateObservableForDecisionState(); foreach (var observer in decisionMakingObservers) { observer.Observe(this); } } public IObservable<IEvent<DecisionState>> Situation { get; private set; } event EventHandler<DecisionState> DecisionStateHasUpdated; void CreateObservableForDecisionState() { Situation = Observable.FromEvent<DecisionState>( ev => this.DecisionStateHasUpdated += ev, ev => this.DecisionStateHasUpdated -= ev); } public void UpdateState(Action<DecisionState> decisionStateUpdate) { decisionStateUpdate(InternalDecisionState); DecisionStateHasUpdated(this, InternalDecisionState); } protected DecisionState InternalDecisionState { get { return internalDecisionState ?? (internalDecisionState = new DecisionState()); } } }

To make this generic I start with a StateKeeper (compiler errors shown in red and I'm omitting any StateKeeper specific specs in this email for brevity):

    public abstract class StateKeeper<State> : IUpdateState<State>
    {

    }

    public interface IUpdateState<State>
    {
        void UpdateState(Action<State> stateUpdate);
    }

I have a new generic interface to replace the specific IUpdateDecisionState and I'm not implementing the underlying member, so have a compilation error. I introduce that member and pull the code from the original state keeper in:

    public abstract class StateKeeper<State> : IUpdateState<State>
    {
        public void UpdateState(Action<State> stateUpdate)
        {
            stateUpdate(InternalState);
            StateHasUpdated(this, InternalState);
        }
    }

I need to pull more code in from the original class to make this work:

    public abstract class StateKeeper<State> : IUpdateState<State>
    {
        State internalState;

        State InternalState
        {
            get
            {
                return internalState ?? (internalState = xxxx? );
            }
        }

        protected event EventHandler<State> StateHasUpdated;

        public void UpdateState(Action<State> stateUpdate)
        {
            stateUpdate(InternalState);
            StateHasUpdated(this, InternalState);
        }
    }

I've now got two issues - the State generic type does not derive from EventArgs and I need to be able to create a new State if the internal state is not available. I can fix both issues with the following:

    public abstract class StateKeeper<State> : IUpdateState<State>
        where State : EventArgs
    {
        State internalState;

        State InternalState
        {
            get
            {
                return internalState ?? (internalState = EnsureThatStateHasBeenCreated());
            }
        }

        protected abstract State EnsureThatStateHasBeenCreated();

        protected event EventHandler<State> StateHasUpdated;

        public void UpdateState(Action<State> stateUpdate)
        {
            stateUpdate(InternalState);
            StateHasUpdated(this, InternalState);
        }
    }

I now have an abstract method to ensure that the state gets created and I have a generic type constraint on my class.
My next step is to make the IKeepDecisionState interface more generic:

    public interface IKeepState<State>
    {
        IObservable<IEvent<State>> Situation { get; }
    }

The StateKeeper also needs to implement this interface and I pull in the constructor code from the DecisionStateKeeper:

    public abstract class StateKeeper<State> : IUpdateState<State>, IKeepState<State>
        where State : EventArgs
    {
        State internalState;

        State InternalState
        {
            get
            {
                return internalState ?? (internalState = EnsureThatStateHasBeenCreated());
            }
        }

        protected abstract State EnsureThatStateHasBeenCreated();

        protected event EventHandler<State> StateHasUpdated;

        public void UpdateState(Action<State> stateUpdate)
        {
            stateUpdate(InternalState);
            StateHasUpdated(this, InternalState);
        }

        public IObservable<IEvent<State>> Situation { get; private set; }

        public StateKeeper()
        {
            CreateObservableForDecisionState();
        }
    }

I now have my observable at the bottom of this class and I have the constructor from the old DecisionStateKeeper.
This now presents me with a problem - I can make this method an abstract method but this would be bad thing to do.

Calling a virtual method from a constructor is a very bad idea - the base class constructors are called before the derived version so it is not good practice to call out to the derived class until it has been initialised.
I therefore need to move this to the situation property itself when it is accessed:

    public abstract class StateKeeper<State> : IUpdateState<State>, IKeepState<State>
        where State : EventArgs
    {
        IObservable<IEvent<State>> situation;
        State internalState;

        State InternalState
        {
            get
            {
                return internalState ?? (internalState = EnsureThatStateHasBeenCreated());
            }
        }

        protected abstract State EnsureThatStateHasBeenCreated();

        protected abstract IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();

        protected event EventHandler<State> StateHasUpdated;

        public void UpdateState(Action<State> stateUpdate)
        {
            stateUpdate(InternalState);
            StateHasUpdated(this, InternalState);
        }

        public IObservable<IEvent<State>> Situation
        {
            get
            {
                return situation ?? ( situation = EnsureThatTheObservableHasBeenCreated());
            }
        }

        public StateKeeper() { }
    }

I now create the observable situation when it is first accessed and there is an abstract method to ensure this happens.

The final piece of this generic work is to introduce the observers - I need a generic interface for this to replace the IObserveToMakeDecisions interface that took in a DecisionStateKeeper and made observations on it:

    public interface IContextObserver<State>
    {
        void Observe(IKeepState<State> stateKeeper);
    }

To implement this in the StateKeeper I have two choices: I can either use IContextObserver<State> directly or I can declare another generic type for the observers, abstracting that interface type. Samples of both are shown below:

    public abstract class StateKeeper<State> : IUpdateState<State>, IKeepState<State>
        where State : EventArgs
    {
        IEnumerable<IContextObserver<State>> observers;

        public StateKeeper(IEnumerable<IContextObserver<State>> observers) { }
    }

    public abstract class StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
        where Observer : IContextObserver<State>
        where State : EventArgs
    {
        IEnumerable<Observer> observers;

        public StateKeeper(IEnumerable<Observer> observers) { }
    }

I prefer the second option so am going to run with that. I now implement the observers in full:

    public abstract class StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
        where Observer : IContextObserver<State>
        where State : EventArgs
    {
        IObservable<IEvent<State>> situation;
        State internalState;

        State InternalState
        {
            get
            {
                return internalState ?? (internalState = EnsureThatStateHasBeenCreated());
            }
        }

        protected abstract State EnsureThatStateHasBeenCreated();

        protected abstract IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();

        protected event EventHandler<State> StateHasUpdated;

        public void UpdateState(Action<State> stateUpdate)
        {
            stateUpdate(InternalState);
            StateHasUpdated(this, InternalState);
        }

        public IObservable<IEvent<State>> Situation
        {
            get
            {
                return situation ?? ( situation = EnsureThatTheObservableHasBeenCreated());
            }
        }

        public StateKeeper(IEnumerable<Observer> observers)
        {
            foreach (var observer in observers)
            {
                observer.Observe(this);
            }
        }
    }

I've now got my first cut of this generic class and this changes the Decision State Keeper and the future Manipulation State Keeper dramatically.
I'll leave you with the now more lightweight and cleaner Decision State Keeper and in my next post I'll discuss one of the domain driven design issues with the observers themselves that is caused by this change.

    public class DecisionStateKeeper : StateKeeper<DecisionState, IObserveToMakeDecisions>
    {
        public DecisionStateKeeper(IEnumerable<IObserveToMakeDecisions> observers) 
                                                                   : base(observers)
        {
        }

        protected override DecisionState EnsureThatStateHasBeenCreated()
        {
            return new DecisionState();
        }

        protected override IObservable<IEvent<DecisionState>> 
                                           EnsureThatTheObservableHasBeenCreated()
        {
            return Observable.FromEvent<DecisionState>(
                ev => this.StateHasUpdated += ev,
                ev => this.StateHasUpdated -= ev);
        }
    }

    public interface IObserveToMakeDecisions : IContextObserver<DecisionState>
    {
    }

Posted at at 8:17 AM on Thursday, October 7, 2010 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,