Thursday, August 25, 2011

Using a "Selection Strategy” to Simplify Your Code

(I wrote blog post this in April of 2010 but never published it. I am no longer an employee of Dovetail Software but at the time of this post I was working on their awesome Support Suite product with some amazing developers. I believe that this post has some good content, so I wanted to publish it before it got lost forever. I apologize for the terrible code formatting; Blogger just stinks at this.)

Very recently Chad Myers and I implemented this pattern in two different places for two very different situations in our Dovetail Support Suite codebase. One was with a “Flash Service”, where based on which entity was passed in, we would call a method on that entity and return the flashes to the caller. The other dealt with displaying values in a menu strip, and based on the entity type or interface, we would have different output returned to the strip.

Why Go To All This Trouble?

Using this pattern has the following benefits:
  1. Prevents us from having a lengthy conditional logic statements in the code, which is less maintainable and harder to read and test. (Very non-OOP procedural code!)
  2. Allows us to create new strategies without modifying the existing service, other strategies, and likely not even the StructureMap bootstrap methods
  3. Allows us to write unit tests for each strategy independently
  4. Adds an extensibility point: We have the defaults wired-up, but you can easily drop an assembly in a directory, have StructureMap scan it and put that at the front of the list.
I chose the display scenario that I mentioned above for my code example only because it handles a couple more selection possibilities that I can demonstrate for my object matching. I created a simple school domain model with an instructor, a course, and a facility. We wrote the code in a Test-Driven manner, but I am not going through that process in this post.

“The Code”

We start off with an interface for a service with a GetDisplayFor method. The idea is that we will pass an entity into the service, which will cycle through a list of strategies until one matches. The matched-strategy will know how to display the output and return it. Each entity has a base method called “EntityDescription” which would be called in other places in the application, but for this specific scenario we need to output something different, which is why this service exists.

public interface IDisplayService
{
  string GetDisplayFor(DomainEntity entity);
}

We then created a class called DisplayService that implements IDisplayService and takes in a collection of IDisplayStrategies into the constructor. We created a DefaultDisplayStrategy, it’s purpose is to be a “catch all” if no other strategies match.

public interface IDisplayStrategy
{
  bool Matches(DomainEntity entity);
  string GetEntityDescription(DomainEntity entity);
}

public class DefaultDisplayStrategy : IDisplayStrategy
{
public bool Matches(DomainEntity entity)
{
return true;
}

  public string GetEntityDescription(DomainEntity entity)
  {
return entity.EntityDescription;
}
}


Here is the code for the DisplayService:

public class DisplayService : IDisplayService
{
private readonly List<IDisplayStrategy> _strategies = new List<IDisplayStrategy>();


public DisplayService(IEnumerable<IDisplayStrategy> strategies)
{
_strategies.AddRange(strategies);
_strategies.Add(new IdentifierDisplayStrategy());
_strategies.Add(new DefaultDisplayStrategy());
}

public string GetDisplayFor(DomainEntity entity)
{
var strategy = FindStrategyFor(entity);
return strategy.GetEntityDescription(entity);
}

public IDisplayStrategy FindStrategyFor(DomainEntity entity)
{
return _strategies.First(s => s.Matches(entity));
}
}

The container will fire in any concrete implementations of IDisplayStrategy that we wired up with StructureMap (code listed later in this post) into the constructor, and since we care about ordering, we “new up” two strategies after those. In the very least, we want the”catch all” to be last.(We asked our teammate, Jeremy D.  Miller, if there is a way to order with StructureMap, and he confirmed there you cannot).

Strategy Unit Testing

As I stated earlier, since we don’t have some monolific conditional logic statement, we can more easily test each piece of our solution. Let’s look at the InstructorDisplayStrategy:

public class InstructorDisplayStrategy : IDisplayStrategy
{
public bool Matches(DomainEntity entity)
{
return entity.GetType() == typeof (Instructor);
}

public string GetEntityDescription(DomainEntity entity)
{
return "Professor " + ((Instructor) entity).Name;
}
}


To test this class, I am using some helpful testing extension methods included in the FubuMVC.Tests project. We basically just need to test what will match and what will not match with the Matches method, and then what our expected output will be on the GetEntityDescription method.

[TestFixture]
public class InstructorDisplayStrategyTester
{
private InstructorDisplayStrategy _strategy;

  [SetUp]
public void Setup()
{
_strategy = new InstructorDisplayStrategy();
}

[Test]
public void should_match_on_instructor_entity()
{
_strategy.Matches(new Instructor()).ShouldBeTrue();
}

[Test]
public void should_not_match_on_non_instructor_objects()
{
_strategy.Matches(new Course()).ShouldBeFalse();
  }
 
[Test]
  public void should_return_description_and_appended_title_for_the_instructor()
{
var course = new Instructor() { Name = "Skippy" };
_strategy.GetEntityDescription(course).ShouldEqual("Professor Skippy");
}
}


The DisplayService fires through the DisplayStrategies and executes the Matches method on each. This one above just tries to match types. The one below tries to match by Interface (“is” is like “as”, except it does not actually try to cast to the provided type, more info here)

public class IdentifierDisplayStrategy : IDisplayStrategy
{
public bool Matches(DomainEntity entity)
{
return entity is IHaveIdentifier;
}
 
public string GetEntityDescription(DomainEntity entity)
{
var identifierEntity = entity as IHaveIdentifier;
return identifierEntity.Identifier + " " + entity.EntityDescription;
}
}

Very familiar looking test:

[TestFixture]
public class IdentifierDisplayStrategyTester
{
private IdentifierDisplayStrategy _strategy;
[SetUp]
public void Setup()
{
_strategy = new IdentifierDisplayStrategy();
}

[Test]
public void should_match_on_identifier_object()
{
_strategy.Matches(new Course()).ShouldBeTrue();
}

[Test]
public void should_not_match_on_non_identifier_object()
{
_strategy.Matches(new DomainEntity()).ShouldBeFalse();
}

[Test]
public void should_return_description_with_identifier_for_the_course()
{
var course = new Course() {Identifier = "1005", Name = "Skippy"};
_strategy.GetEntityDescription(course).ShouldEqual("1005 Skippy");
}
}

I may as well post the last bit of code for the lazy folks that don’t want to download the source. Here is the unit test for the DisplayService. (Again, you will notice some assertion and mocking shorthand through the use of the helpful extension methods.) We are testing the ordering, that the default is called if no others match, and basically that the service’s methods behave how we intended (this statement is slightly untrue because this unit test file was were we started and drove out the functionality of the service with the tests below).

[TestFixture]
public class DisplayServiceTester
{
private DisplayService _displayService;
private IDisplayStrategy _strategy;
private IDisplayStrategy _strategy2;

[SetUp]
public void Setup()
{
_strategy = MockRepository.GenerateStub<IDisplayStrategy>();
_strategy2 = MockRepository.GenerateStub<IDisplayStrategy>();
_displayService = new DisplayService(new[] { _strategy, _strategy2 });
}

[Test]
public void should_return_default_empty_entity_description_if_no_strategy_matched()
{
_displayService.GetDisplayFor(new DomainEntity()).ShouldEqual("");
}

[Test]
public void should_return_default_strategy_no_matter_what()
{
_displayService.FindStrategyFor(new DomainEntity()).ShouldBeOfType<DefaultDisplayStrategy>();
  }

  [Test]
public void should_match_a_strategy_by_matches_method()
{
_strategy.Stub(x => x.Matches(null)).IgnoreArguments().Return(true);
_displayService.FindStrategyFor(new DomainEntity()).ShouldBeTheSameAs(_strategy);
}

[Test]
public void should_match_first_strategy()
{
_strategy.Stub(x => x.Matches(null)).IgnoreArguments().Return(true);
_displayService.FindStrategyFor(new DomainEntity());
_strategy2.AssertWasNotCalled(s => s.Matches(null), o => o.IgnoreArguments());
}

[Test]
public void should_check_all_strategies_for_matches()
{
_strategy2.Stub(x => x.Matches(null)).IgnoreArguments().Return(true);
_displayService.FindStrategyFor(new DomainEntity()).ShouldBeTheSameAs(_strategy2);
  }

  [Test]
  public void should_return_display_from_matched_strategy()
{
string name = "Skippy";
_strategy.Stub(x => x.Matches(null)).IgnoreArguments().Return(true);
   _strategy.Stub(x => x.GetEntityDescription(null)).IgnoreArguments().Return(name);
   _displayService.GetDisplayFor(new DomainEntity()).ShouldEqual(name);
  }

  [Test]
  public void should_only_call_display_on_matched_method_and_no_others()
{
_strategy.Stub(x => x.Matches(null)).IgnoreArguments().Return(true);
    _strategy.Stub(x => x.GetEntityDescription(null)).IgnoreArguments().Return(null);
_displayService.GetDisplayFor(new DomainEntity());
_strategy2.AssertWasNotCalled(x => x.GetEntityDescription(null), o => o.IgnoreArguments());
}
}


Usage in the Controller

The controller takes the display service into the constructor and grabs the implementation from the container. All the controller method does is call the GetDisplayFor method on the service and passes in an object that subclasses DomainEntity. The service returns a string, the controller plugs it into the view model and then returns it to the view. (I am using FubuMVC for my example, so don’t be thrown off by the input view model and the output view model)

1: public class HomeController
2: {
3: private readonly IDisplayService _displayService;
4:  
5: public HomeController(IDisplayService displayService)
6: {
7: _displayService = displayService;
8: }
9: 
10: public HomeViewModel Home(HomeInputModel input)
11: {
12: var course = _displayService.GetDisplayFor(new Course() { Name = "Lance", Identifier = "1005"});
13: return new HomeViewModel { Text = course };
14: }
15: }
16: 
17: public class HomeInputModel
18: {
19: }
20: 
21: public class HomeViewModel
22: {
23: public string Text { get; set; }
24: }



Wiring Up the Container

In the global.asax Application_Start we wire up the following:


1: ObjectFactory.Initialize(x =>
   2: {
   3:     x.Scan(y =>
   4:                {
   5:                    y.AssemblyContainingType<IDisplayService>();
   6:                    y.WithDefaultConventions();
   7:                });
   8:     x.For<IDisplayStrategy>().Use<InstructorDisplayStrategy>();
   9: }

Why only the one concrete class? If you recall, we have the last resort DefaultDisplayStrategy and the IdentifierDisplayStrategy “newed up” inside the DisplayService construction because ordering is important. Why not just “new up” the last strategy in the constructor as well? Because this is just a small example and the beginning of many more strategies that will be added, also as mentioned above, this is an extensibility point.

If ordering did not matter, we could remove the object instantiations from the DisplayService constructor and let StructureMap wire it all up like this(which is also an example that could be used for the extensibility point scanning):


1: ObjectFactory.Initialize(x =>
2: x.Scan(y => {
3: y.AssemblyContainingType<IDisplayService>();
4: y.WithDefaultConventions();
5: y.AddAllTypesOf<IDisplayStrategy>();
6: })
7: );


Conclusion

There you have it. Hopefully this post will help you to solve similar problems in the future.

Code posted here.


~ Tim Tyrrell

1 comments:

Tim Tyrrell August 25, 2011 at 9:55 AM  

Damnit, it is stomping my generics. Trying to fix.