[EnhanceYourCode] : the Builder Pattern, Part2

Builder

Hello,

In the previous article, we explored the theory of the builder pattern.

Let’s see a more concrete example :

Let’s assuming that we are building a Role Playing Game core model. Here are the basic rules:

  • A player can be a Hero : a Warrior, a Wizard, or a Thief (we keep it simple)
  • Every Hero has 4 main characteristics: Health, Strength, Spirit, and Speed, that are counted in points.
  • Heroes have a Level, and starting characteristics are based on this level (Health starts at Level * 10, Strength and Spirit start at Level * 5, and Speed starts at Level * 3)
  • Warrior has a (+2 Strength, -2 Spirit) Modificator, Wizard has (+2 Spirit, -2 Strength) Modificator
  • Player can improve 2 Characteristics of 1 points each or 1 characteristic of 2 points, in order to cutomize his Hero.

A naive implementation of the Hero class would be :

namespace Blog.RolePlayingGame.Core
{
public interface ITarget
{
void ReceivePhysicalAttack(int strength);
void ReceiveMagicalAttack(int strength);
}
public class Hero
{
public HeroClass Class { get; private set; }
public string Name { get; private set; }
public int Level { get; private set; }
public int Health { get; private set; }
public int Strength { get; private set; }
public int Spirit { get; private set; }
public int Speed { get; private set; }
public Hero(HeroClass @class, string name, int level, int health, int strength, int spirit, int speed)
{
Class = @class;
Name = name;
Level = level;
Health = health;
Strength = strength;
Spirit = spirit;
Speed = speed;
}
public void Hit(ITarget target)
{
target.ReceivePhysicalAttack(this.Strength);
}
public void Spell(ITarget target)
{
target.ReceiveMagicalAttack(this.Spirit);
}
}
public enum HeroClass
{
Warrior = 1,
Wizard = 2,
Thief = 3
}
}

view raw
Hero_naive.cs
hosted with ❤ by GitHub

Let’s focus on the Hero Creation : Every Heroes are of the same kind : Indeed, despite of the different classes, every Hero has the same kind of characteristics. So, there is no need for a specific class reflecting the “Hero Class”.

Here is a first test (Note that I use Fixie test framework and Shouldly assertion library, i’ll post about it soon):

using Shouldly;
namespace Blog.RolePlayingGame.Core.Tests
{
public class HeroBuilderTests
{
public void An_HeroBuilder_can_build_a_warrior()
{
Hero actual = new HeroBuilder()
.OfWarriorClass()
.Create();
actual.Class.ShouldBe(HeroClass.Warrior);
}
}
}

We want to be sure that our builder can build a warrior. So the implementation is straigth-forward :

namespace Blog.RolePlayingGame.Core
{
public class HeroBuilder
{
private HeroClass _class;
public HeroBuilder OfWarriorClass()
{
_class = HeroClass.Warrior;
return this;
}
public Hero Create()
{
return new Hero(@class: _class,
name: _name ,
level:1,
health: _health,
strength: 0,
spirit: 0,
speed: 0);
}
}
}

Obviously, we can add the methods for the other classes (keep in mind that the scope is really thin).
Next step would be to ensure we cannot build a Hero without a class. The test would be :

public void An_HeroBuilder_cannot_build_a_hero_without_class()
{
Action tryToBuildAHeroWithoutClass = () => new HeroBuilder().Create();
tryToBuildAHeroWithoutClass.ShouldThrow<HeroBuilder.BuildingHeroWithoutClassAttempException>();
}

So we update the Builder accordingly :

namespace Blog.RolePlayingGame.Core
{
public class HeroBuilder
{
private HeroClass _class;
public HeroBuilder OfWarriorClass()
{
_class = HeroClass.Warrior;
return this;
}
public Hero Create()
{
if( IsClassNotSettled())
throw new BuildingHeroWithoutClassAttempException();
return new Hero(@class: _class,
name: _name ,
level:1,
health: _health,
strength: 0,
spirit: 0,
speed: 0);
}
public class BuildingHeroWithoutClassAttempException : Exception
{
public BuildingHeroWithoutClassAttempException() : base ("Cannot creating an hero without class") { }
}
}
}

The guard occurs in the Create Method because it’s the most convenient place to place it, for the moment.

By following our “Business Rules”, we end-up with this kind of class :

using System;
namespace Blog.RolePlayingGame.Core
{
public class HeroBuilder
{
private HeroClass _class;
private int _level;
private int _health;
private int _strength;
private int _spirit;
private int _speed;
private string _name;
private CharacteristicsModificator _modificator;
private readonly CharacteristicBoosterSet _boosterSet = new CharacteristicBoosterSet();
private bool _dolevelComputation = true;
public HeroBuilder()
{
_level = 1;
}
public HeroBuilder OfWarriorClass()
{
_class = HeroClass.Warrior;
_modificator = new CharacteristicsModificator(strength: 2, spirit: 2);
return this;
}
public HeroBuilder OfWizardClass()
{
_class = HeroClass.Wizard;
_modificator = new CharacteristicsModificator(strength: 2, spirit: 2);
return this;
}
public HeroBuilder OfThiefClass()
{
_class = HeroClass.Thief;
_modificator = CharacteristicsModificator.Void;
return this;
}
public HeroBuilder WithName(string name)
{
_name = name;
return this;
}
public HeroBuilder WithLevel(int level)
{
_level = level;
_health = _level * 10;
_strength = _level * 5;
_spirit = _level * 5;
_speed = _level * 3;
_dolevelComputation = false;
return this;
}
public HeroBuilder BoostStrength(BoostCharacteristics boost = BoostCharacteristics.OfOne)
{
_boosterSet.BoostStrength(boost);
return this;
}
public HeroBuilder BoostSpirit(BoostCharacteristics boost = BoostCharacteristics.OfOne)
{
_boosterSet.BoostSpirit(boost);
return this;
}
public Hero Create()
{
if (IsClassNotSettled())
throw new BuildingHeroWithoutClassAttempException();
if (IsNameNotSettled())
throw new BuildingHeroWithoutNameAttempException();
if (_dolevelComputation)
WithLevel(1);
ApplyModificator();
ApplyBoost();
return new Hero(@class: _class,
name: _name,
level: _level,
health: _health,
strength: _strength,
spirit: _spirit,
speed: _speed);
}
private bool IsClassNotSettled()
{
return _class == default(HeroClass);
}
private bool IsNameNotSettled()
{
return string.IsNullOrWhiteSpace(_name);
}
private void ApplyModificator()
{
_strength += _modificator.Strength;
_spirit += _modificator.Spirit;
}
private void ApplyBoost()
{
_strength += _boosterSet.StrengthBoost;
_spirit += _boosterSet.SpiritBoost;
}
public class BuildingHeroWithoutClassAttempException : Exception
{
public BuildingHeroWithoutClassAttempException() : base("Cannot creating an hero without class") { }
}
public class BuildingHeroWithoutNameAttempException : Exception
{
public BuildingHeroWithoutNameAttempException() : base("Cannot creating an hero without name") { }
}
}
}

We actually built a Domain-Specific-Language for our Hero Creation Context. This could seem a bit complex for the purpose at the first sight, but we do acheive a complete separation between the complexity of building a Hero and the behavior of the Hero later in the game.  To illustrate this, we can take a look to a potential implementation of a game client :

using System;
namespace Blog.RolePlayingGame.Core
{
class Program
{
static void Main(string[] args)
{
var myHero = new HeroBuilder()
.OfWarriorClass()
.WithName("Mighty Hall-Dard")
.WithLevel(2)
.BoostStrength()
.BoostSpirit()
.Create();
var enemy = new Monster();
myHero.Hit(enemy);
}
}
class Monster : ITarget
{
private int health = 15;
private int _strength = 3;
private int _spirit = 3;
public void ReceivePhysicalAttack(int incomingStrength)
{
health -= Math.Max(0, (incomingStrength _strength));
}
public void ReceiveMagicalAttack(int strength)
{
throw new NotImplementedException();
}
}
}

In this article, we saw how to implement the Builder Design Pattern in C# in a Fluent Interface way.

You can find the source code in this github repository

[EnhanceYourCode] : the Builder Pattern

Builder

Hello,

In this article, I’d like to present you the Builder pattern and how I use it in my C# code.

The Builder Pattern is a Creational design pattern, like the Factory Method Pattern I already covered un this previous article. Its main focus is to provide a light DSL to build objects by settings startup properties, by seperating the process of constructing an object from the object itself.

Basically, the idea is to create a class with mutable fields, that will be initialized with dedicated methods, and a final method that create the object itself from thoses values. Here is an abstract example :

using System;
namespace Builder
{
public class MyClass
{
private readonly string _aStringProperty;
private readonly bool _aGivenFlag;
private readonly bool _anotherFlag;
public MyClass(string aStringProperty, bool aGivenFlag, bool anotherFlag)
{
_aStringProperty = aStringProperty;
_aGivenFlag = aGivenFlag;
_anotherFlag = anotherFlag;
}
public object DoSomeBehavior()
{
dynamic @object = null;
@object.actionAt = DateTime.UtcNow;
@object.theName = _aStringProperty;
if (_aGivenFlag)
@object.theName = "the property : " + @object.theName;
if (_anotherFlag)
@object.theName = @object.theName.ToLower();
return @object;
}
}
}

This class is pretty straight forward : it’s an immutable object that perform some behavior. Nothing wrong here, but it’s construction elsewhere in the code can be a little painful, because we have to know how this class works internally to give the correct parameters to its constructor.

using System;
namespace Builder
{
public class MyPoorClassClient
{
public void ExecuteTheDefaultUseCase()
{
var myClass = new MyClass("the name to use", false, false);
var theResult = myClass.DoSomeBehavior();
}
public void ExecuteAnotherUseCase()
{
var myClass = var myClass = new MyClass("the first another one", true, true);
var theResult = myClass.DoSomeBehavior();
}
}
}

How can we enhance this construction, how can we make this kind of code more readable therefore more maintainable?
This is the purpose of the Builder Pattern. It will allow you to craft a nice and intent-revealing way to build your object :

using System;
namespace Builder
{
public class MyClassBuilder
{
private string _aNameToSet;
private bool _prependPropertyDescriptor = false;
private bool _lowerizeOutput = false;
public MyClassBuilder SetTheName(string aNameToSet)
{
_aNameToSet = aNameToSet;
return this;
}
public MyClassBuilder PrependPropertyDescriptor()
{
_prependPropertyDescriptor = true;
return this;
}
public MyClassBuilder LowerizeOutput()
{
_lowerizeOutput = true;
return this;
}
public MyClass Build()
{
return new MyClass(_aNameToSet, _prependPropertyDescriptor, _lowerizeOutput);
}
}
}

Note that all the builder’s methods return the builder itself, so we can compose a Fluent Interface that will improve the readability, again.

using System;
namespace Builder
{
public class MyClassClient
{
public void ExecuteTheDefaultUseCase()
{
var myClass = new MyClassBuilder()
.SetTheName("the first use case is simple")
.Build();
var theResult = myClass.DoSomeBehavior();
}
public void ExecuteAnotherUseCase()
{
var myClass = new MyClassBuilder()
.SetTheName("the first another one")
.PrependPropertyDescriptor()
.LowerizeOutput()
.Build();
var theResult = myClass.DoSomeBehavior();
}
}
}

Our code could now seem more than before, but we actually gain a lot of simplicity, and we don’t need to dive into the MyClass definition anymore to know how it behaves.

I will soon post a less theorical article about this pattern, keep in touch!

[EnhanceYourCode] : the Factory Method Pattern

Dead factory – Alexander Kaiser – This file is licensed under the Creative Commons Attribution 2.0 Generic license.

The Factory Method pattern is, in my opinion, one of the most useful creational design patterns.

It allows us to delegate the creation of an object to a dedicated class, and thus encapsulate all the logic of this creation that is often not directly related to the responsibility of the class.

1) Simple example :
Given the following code :

using System;
namespace Oinant.Blog.Factory.SimpleExemple
{
public class MyBusinessObject
{
private string _content;
private DateTime _dateTimeReleventToBusinessLogic;
public MyBusinessObject(Tuple<DateTime, String> creationData)
{
_content = creationData.Item2;
_dateTimeReleventToBusinessLogic = creationData.Item1;
}
public bool IsBusinessRequirementMet()
{
return !string.IsNullOrEmpty(_content);
}
public void PerformBusinessLogic()
{
}
public string GetContent()
{
return _content;
}
}
class MyBusinessObjectFactory
{
private readonly IBusinessRepository _businessRepository;
public MyBusinessObjectFactory(IBusinessRepository businessRepository)
{
_businessRepository = businessRepository;
}
public MyBusinessObject Create(Guid id)
{
var content = _businessRepository.GetContent(id);
return new MyBusinessObject(new Tuple<DateTime, string>(DateTime.Now, content));
}
}
public class Client
{
private void Run()
{
var factory = new MyBusinessObjectFactory(new DummyBusinessRepository());
var myRunnerId = new Guid();
MyBusinessObject myObject = factory.Create(myRunnerId);
if(myObject.IsBusinessRequirementMet())
myObject.PerformBusinessLogic();
}
}
public interface IBusinessRepository
{
string GetContent(Guid id);
}
public class DummyBusinessRepository : IBusinessRepository
{
public string GetContent(Guid id)
{
return id.ToString();
}
}
}

view raw
BasicFactory.cs
hosted with ❤ by GitHub

The first class is an actual business object : It’s built from some properties, has some business logic. Its single responsibility is to perform business logic. It shouldn’t embed any infrastructural concern ( like database connection for example)

The second class is the factory itself, that handle the full creation process of our BusinessObject. Its responsibility includes to fetch data from a repository, and to call the business class constructor.

The third class is a simple runner, that instanciate the factory, get the business object from it, and perform what the program is meant to do. Thanks to the Factory Method Pattern, the Runner is not polluted with any construction logic, everything is delegated to the factory object.

2) Increase the system testability:
Obviously, by splitting the responsibilities of your code into different modules, you are, de facto, improving the testablity of your program.
But in some cases, you can use the factory method pattern as a way to use a TestDouble where your usual mocking techniques cannot apply.
For example, when your code is consuming an external object, and that object has no interface, like this NetworkMessage.

using System;
namespace ExternalLibrary
{
public class NetworkMessage
{
static readonly TimeSpan TimeToLive = TimeSpan.FromSeconds(10);
private readonly DateTime _creation;
private Status _status;
private readonly object _content;
public NetworkMessage(Status status, object content)
{
_creation = DateTime.UtcNow;
_status = status;
_content = content;
}
public bool IsSuccess()
{
if (HasTimedOut())
_status = Status.Failed;
return _status == Status.Succeeded;
}
private bool HasTimedOut()
{
return (_creation.Add(TimeToLive)) < DateTime.UtcNow;
}
public T GetContentAs<T>() where T : class
{
var castedContent = _content as T;
if (castedContent == null)
throw new InvalidCastException("contet couldn't be casted into " + typeof(T));
return _content as T;
}
}
public enum Status
{
Pending,
Succeeded,
Failed
}
public class NetworkService
{
public Tuple<int, object> SendMessage()
{
// for ske of simplicity, some static data…
return new Tuple<int, object>(1, new object());
}
}
}

As you can see, the main class relies on DateTime.Now, that make the code relying on it quite complicated to test.

Here is our own NetworkClient, without factory for the NetworkMessage :

using ExternalLibrary;
namespace Oinant.Blog.Factory.ForTesting
{
public class NetworkClientWithoutMessageFactory
{
public string SendRequest()
{
var message = new NetworkService().SendMessage();
var networkMessage = new NetworkMessage((Status)message.Item1, message.Item2);
return networkMessage.IsSuccess().ToString() + " " + networkMessage.GetContentAs<string>();
}
}
}

Here, in order to be able to test every execution path of our client, we have to know precisely how the external library behaves internally, and even use some Microsoft.Fakes to create shims of System.DateTime. That’s a lot of test code that is not really relevant, because it’s out of our scope. Futhermore, we just want to control the NetworkMessage output in order to ensure that our network client behaves correctly.
To achieve this, we can add a factory to our client :

using ExternalLibrary;
namespace Oinant.Blog.Factory.ForTesting
{
public class NetworkClientWithMessageFactory
{
private readonly INetworkMessageFactory _networkMessageFactory;
public NetworkClientWithMessageFactory(INetworkMessageFactory networkMessageFactory)
{
_networkMessageFactory = networkMessageFactory;
}
public string SendRequest()
{
var message = new NetworkService().SendMessage();
var networkMessage = _networkMessageFactory.Create((Status)message.Item1, message.Item2);
return networkMessage.IsSuccess().ToString() + " " + networkMessage.GetContentAs<string>();
}
}
public interface INetworkMessageFactory
{
NetworkMessage Create(Status status, object content);
}
public class ConcreteNetworkMessageFactory : INetworkMessageFactory
{
public NetworkMessage Create(Status status, object content)
{
return new NetworkMessage(status, content);
}
}
}

And testing becomes really easy, by implementing another factory, that creates an object which inherits from our external object :

using ExternalLibrary;
using Oinant.Blog.Factory.ForTesting;
namespace Factory.Tests
{
public class TestFactory : INetworkMessageFactory
{
public NetworkMessage Create(Status status, object content)
{
var message = new NetworkMessageDouble(status, content);
return message;
}
}
class NetworkMessageDouble : NetworkMessage
{
private readonly Status _status;
private readonly object _content;
public NetworkMessageDouble(Status status, object content) : base(status, content)
{
_status = status;
_content = content;
}
public new bool IsSuccess()
{
return _status == Status.Succeeded;
}
public T GetContentAs<T>() where T : class
{
return _content as T;
}
}
}

In this article, we saw that the Factory Method pattern helps us respecting the SOLID’s Single Responsibility Principle, and can help us with external/legacy code integration, by providing us a way to enhance testability.

Note : all the code of this article is accessible on this github repository Continue reading