[EnhanceYourCode] : the Builder Pattern, Part2



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


[EnhanceYourCode] : the Builder Pattern



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!

Canopy : Automate your browser tests the F# way!



I’d like to introduce you Canopy, a Selenium overlay written in F#. It brings you the concision and the clarity of F# to your selenium tests.

First of all, we have to create a new F# console application, then we install canopy in our project: canopytryout-install-package

As you can see, the canopy nuget will bring back the selenium ecosystem.

Lets create our first test. It will check that a search of “canopy F#” in google will feature the official Canopy website as the first result. Here is the little bootstrapping needed by Canopy :

Fisrt, we load the dependencies : the canopy core libray (of course) and the canopy runner, that is basically a wrapper over the selenium driver,
Then we start a browser (firefox, for instance).

After that come the body of the test itself (we see it later), and the instruction to run the test suite. The quit() instruction will handle everything to finalize the test run, like closing the browser.

Let’s take a look at the test itself. Here is an implementation proposal :

It’s a very basic test. The first line is the test case definition.
The test body starts with a navigation to the Google’s homepage.
Then, we fill the search field with the “Canopy F#” value. Here is a little subtility here, with the way the Google homepage works: as soon we start to type, the page layout changes, the search box shows a kind of dropdown list with search suggestion. Once the search word is fully typed into the search box, we click on the search button.
Then we click on the first result in the results list.
Finally, we can make our assertion. In this case, the ‘on “url”‘ will assert that we are on the expected page.


Are we done? No!
The test code as to be as clean as the production code, so lets do some refactoring.
We can start by applying the page object pattern: it’s a way to abtract a page, and to encapsulate its behaviour, so the test become way more readable.

Lets add a google.fs file to our solution (do not forget to move it above program.fs)

with the following content :

Here, i just extract the interactions with the Google homepage.
It greatly simplifies my test case, which becomes :

That’s all for this first Canopy Automation & Testing framework and the Page Object pattern in F#. More to come about this soon!

P.S. : You can find the source code for this example on my github repo.

[Node.js] Build a clean process manager

In this article, I’ll demonstrate how to buid a simple and maintainable process manager for Node.js, leveraging its Event Loop.

The main idea is have a core processor that will be able to run a serie of tasks, in a synchronous way.
As you may know, Javascript is by essence an asynchronous language.
Let take simple example :

As the execution flow is asynchroneous, the result variable will not be valued before the crawling method ends, and the usage of the variable will occurs before its valuation
The standard solution in javascript to handle this issue is to use a callback method :

Callbacks are really handy, but what happen if if I have a process with several tasks in it?

Yes, we just felt into the Callback Hell!
The main issue with the nested callback is that your code has a lack of readability and flexibility. It’s quite difficult to understand what the code is meant to do. And if you have to modify the process, you’ll have to rethink the whole process.

We can do much better!

NodeJs processing model is based on a event loop, so we can easily use an event-driven approach.
We build a very simple “event bus” :

A task is a function that wrap a logical unit of work and a callback to the event bus:

Note that i use a context object, where task can store some data that following tasks can use, and use data previously setted.

Then we can build the processor. As we want the maximun readability, we want our process to be a declarative list of tasks. So our processor execute tasks in a synchronous way, waiting an event from the event bus before executing the next task :

Then, the definition of the process itself :
We first gather all the needed components, then simply build an array of the task in the needed order:

We are done! We now have a nicely decoupled task processor, and we now focus on writing unit of work that will be wrapped in tasks, so we are now will be able to follow the Single Responsibility Principle.

[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

Are Estimates business critical?

Thanks to my first post, i had the chance to have very interesting chat with some cowokers.

One of the main concern was the mandatory apsect of the estimates in specific situations, mostly in order to arbitrate between two projects.

First of all, let me clarify my thoughts about estimates. In order to provide reliable estimate, the following criteria have to be gathered :

  • Team should know itself perfectly, knowing precisely what are the strenghts and weakness of each member.
  • Team’s codebase should be either blank or without defects
  • product should entierely identified and specified, and the Product Owner, as the domain experts, 100% sure of what the final product should be.

I’ll post more on this later, but in my opinion, thoses conditions are at best anti-agile and at worst impossible to get.

Considering this fact, it becomes obvious that in our everyday work, no estimates could be actually accurate. Even if we know our codebase, we are never sure our assumptions are correct. Maybe we’ll have to completely refactor a code area that did not get the initial crafting it deserved?

This lack of precision make estimates a decision making tool of low reliability. Unluckily, estimates are often considered as a sufficient communication tool and justify that product stakholders do not need to work in the same room.
I’d rather like integrated teams, where domain experts, devs, product owners, QAs and Ops are working together, in the same physical place, that facilitate a very short feedback loop, and enable a truly collaborative build of the product. This kind of team often manages to identify then plan achievable user-stories in a sprint, based on business needs. This team’s velocity is now more than a managerial data, but also a value-oriented business data : the number of user-stories going to prod per sprint.

This metric is useful, because it gives more visibility on what a team can achieve in a near future, in a way that is way more reliable and tangible than the traditionnal mand-day estimates.

Another dangerous effect of estimates comes from a psychological aspect : We, developers, are often afraid of failure. When a given task oversteps its original estimates, we feel like we are experiencing a failure. So the estimates tend to become commitment, at the really moment we communicate on it.
When we tell to the team, or managers, that a given task is achievable in one day, we implicitely commit ourselves to perform this task in one day. And two results are possible :

  • the estimate was too optimistic : in order to finish in time, we’ll naturally tend to lower the qualtity of our code
  • the estimate was too pessimistic : we tend to lose focus, and the productivity of the team can be lowered, in a totally unoticeable way.

But we, developers, feel way less guilty in the second case. So what? Naturally, we tend to add a security range when we give our estimates in order to avoid the first case. And this harness is added in percentage. A common practice is to add 30% to the original estimate. Yes, we literally add an “I don’t truly know my system as well as i want” time to an unreliable estimate, just to not being late on our delivery, to make our managers happy!

That’s why, in my opinion, estimates should not be used as a decision aid tool.


This is a daily struggle of the developper nowadays : to give accurate estimates of the work we are doing, or we’ll have to do. When was the last time you succeeded  to give an actually accurate estimate? You know, the one that perfectly fits the amount of work to do, in the exact time frame, with a clear vision of what you were meant to do?  It’s been a while, isn’t it?

How can we do better?

There is several reasons of being asked to estimate a task, a story or even a project.

1) The task/story is allready defined, and the team has to make sure that its aim will fit nicely the team’s ambition (and commitment)  by the end of the sprint. 

This is a complicated situation, that implies you have both a fixed budget and a fixed scope. In this particular case, estimating tasks/stories is a pure waste of time.  You’d better focus on the most critical part of the work, analyse it, design it, code it, but doing planning poker or similar exercises will not, for sure, delayed the deadline nor extend the budget.

2) Business/Management need to arbitrate the next priorities

In this case, the “guys over there” surely  at best want to calculate the ROI. Nothing wrong with that, obvioulsy, but it indicates that they have limited budget. So, why do not ask for the budget directly, and try to build the best possible solution with them?
At worst, Buisness/Management are lacking of vision, so they try to select cheapest projects/features. Yes, you read it right. Some organisations are planning according to the cost instead of the value… If it happen in your company, don’t stay inactive, try to involve the product team, show them how a team of passionnate developers can help them to improve their results by incrementally shipping value to them (and yes, a Continuous Integration environment can help a lot, as a Continuous Delivery process). Invite them to some cooperation workshop (ever heard of EventStorming?) to prove that you are able to speak, and understand their “language”, their problem. Estimates won’t be necessary, because project’s stakeholders will be pleased to ask for change and see that they are part of the team that actually buid their product.

3) Management need to anticipate release dates, to coordinate with other departements / customers

That is, in my opinion, the best reason for a need of estimates. A media campaign to promote a new website has to be planned a long time before its actual launch, for example, and the launch of the website has to be as close as possible to it.  But in this case, the scope cannot be fixed. Developement is an exploratory process. The only way to provide an extremely accurate estimate of a project is basically to break each feature in set of very tiny tasks. But to achieve this, you’ll have to explore your domain, and understand how to organise the software. That is impossible to do without coding it…

So, next time someone ask you for estimates, ask them why they need it. By understanding their needs like your understand their business domain, you’ll build a trust-based relationship.