[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 :

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):

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

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 :

So we update the Builder accordingly :

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 :

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 :

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

Advertisements

[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 :

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.

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 :

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

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 :

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.

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 :

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 :

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

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