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

Canopy : Automate your browser tests the F# way!

OLYMPUS DIGITAL CAMERA

Hello,

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 :


open canopy
open runner
start firefox
"first result for canopy f# in google is the project homepage" &&& fun _ ->
// here com the actual test code
run()
printfn "press [enter] to exit"
System.Console.ReadLine |> ignore
quit()

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 :


"first result for canopy f# in google is the project homepage" &&& fun _ ->
url "https://www.google.com&quot;
"#lst-ib" << "canopy f#"
click "button[name=btnG]"
click (first "div.srg a")
on "http://lefthandedgoat.github.io/canopy/&quot;

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.

Demo:

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)
canopy-tryout-addGoogleFs

with the following content :


namespace PageObjects
module Google =
open canopy
let goToFirstResultFor (search:string) =
url "https://www.google.com&quot;
"#lst-ib" << search
click "button[name=btnG]"
click (first "div.srg a")

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


open PageObjects.Google
"first result for canopy f# in google is the project homepage" &&& fun _ ->
PageObjects.Google.goToFirstResultFor "canopy f#"
on "http://lefthandedgoat.github.io/canopy/&quot;

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 :


function CrawlingAWebPageAndGetLinks(){
// do the stuff the method pretend;
}
(function program(){
var result = CrawlingAWebPageAndGetLinks();
console.log(result);
})();

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 :


function CrawlingAWebPageAndGetLinks(callback){
// do the stuff the method pretend;
var value = Crawler.Get("https://www.google.com/search?q=callback%20hell&quot;);
// then use
callback(value);
}
(function program(){
var callback = function(v){
console.log(v);
};
var result = CrawlingAWebPageAndGetLinks(callback);
})();

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


var results = {};
function checkInDatabase(callback){
results.checkresult = SomeComputationThatTakesTime();
callback();
}
function crawl(callback){
results.crawlingResult = SomeComputationThatTakesTime();
callback();
}
function extractData(callback){
results.data = SomeComputationThatTakesTime();
callback();
}
function saveData(callback){
results.dbAcknowledgementMessage = SomeComputationThatTakesTime();
callback();
}
function displayProcessResult(){
console.log(results);
}
function process (){
checkInDatabase(function(){
crawl(function(){
extractData(function(){
saveData(function(){
displayProcessResult();
});
});
});
});
}

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


var processEvents = {
taskDone: 'taskDone',
taskFaulted: 'taskFaulted',
processDone: 'processDone',
};
module.exports = processEvents;


var processEvents = require('./processEvents.js');
var events = require('events'),
util = require('util');
function ProcessEventBus() {
events.EventEmitter.call(this);
}
util.inherits(ProcessEventBus, events.EventEmitter);
ProcessEventBus.prototype.taskDone = function(data) {
this.emit(processEvents.taskDone, data);
};
ProcessEventBus.prototype.taskFaulted = function(data) {
this.emit(processEvents.taskFaulted, data);
};
ProcessEventBus.prototype.processDone = function(data) {
this.emit(processEvents.processDone, data);
};
module.exports = ProcessEventBus;

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


var Merger = require("../../merger.js");
function mergeCrawlerResults() {
this.execute = function(context, eventBus) {
var taskCompleteCallback = function(data) {
context.crawlerMergeResults = data;
eventBus.taskDone();
}
var merger = new Merger(taskCompleteCallback);
merger.merge(context.crawledNewLinks);
}
}
module.exports = mergeCrawlerResults;

view raw

taskExample.js

hosted with ❤ by GitHub

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 :


var processEvents = require("./processEvents.js"),
ProcessEventBus = require("./processManager/processEventBus.js");
function Processor(process, onCompletion, options) {
options = options || {};
options.logEvents = options.hasOwnProperty('logEvents') ? options.logEvents : false;
options.context = options.hasOwnProperty('context') ? options.context : {};
var eventBus = new ProcessEventBus();
function executeNext() {
if(options.logEvents) console.log('Processor.executeNext, tasks left : ' + process.length);
if (process.length > 0) {
var nextTask = process.shift();
nextTask.execute(options.context, eventBus);
}
else
eventBus.processDone();
}
eventBus.on(processEvents.taskDone, function(data) {
if(options.logEvents) console.log('processEvents.taskDone');
executeNext();
});
eventBus.on(processEvents.processDone, function(data) {
if(options.logEvents) console.log('processEvents.processDone');
onCompletion(context);
});
this.execute = function() {
if(options.logEvents) console.log('Processor.execute, initial tasks count : ' + process.length);
executeNext();
};
}
module.exports = Processor;

view raw

processor.js

hosted with ❤ by GitHub

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:


var // infra & services
Store = require("../../dal.js"),
// process infrastructure
Processor = require("../processManager/processor.js"),
// tasks
GetStoredActiveLinks = require("./tasks/getStoredActiveLinks.js"),
GetAllLinks = require("./tasks/getAllLinks.js"),
Crawl = require("./tasks/crawl.js"),
MergeCrawlerResults = require("./tasks/mergeCrawlerResults.js"),
CheckForDelta = require("./tasks/checkForDelta.js"),
SaveNewLinks = require("./tasks/saveNewLinks.js"),
SaveLinksSummary = require("./tasks/saveLinksSummary.js");
function Process() {
var store = new Store();
var process = [
new GetStoredActiveLinks(store)
, new GetAllLinks(store)
, new Crawl()
, new MergeCrawlerResults()
, new CheckForDelta()
, new SaveNewLinks(store)
, new SaveLinksSummary(store)
];
this.execute = function() {
console.log('new process');
var onProcessComplete = function(result){ console.log("process completed")};
var processor = new Processor(process, onProcessComplete);
processor.execute();
}
};
module.exports = Process;

view raw

Process.js

hosted with ❤ by GitHub

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 :


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

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.

(No)Estimates!

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.