Archive for the ‘Software craftsmanship’ category

Functional DI and breaking language boundaries

September 16, 2010

Today I received a priceless lesson on design, testability, Ioc and the way the boundaries of the development language we know may shape our thinking. It all started with a post by Derick Bailey on design and testability which lit a lively and truly interesting discussion. Derick was basically asking why people tend to demonise TypeMock even though it bares strong similarities to ruby mocking frameworks which are usually hailed by the same people, giving an example of how we tend to abstract dependencies in c# through interfaces, like so:

 public class Foo
private doSomething;

public Foo(IDoSomething doSomething)
this.doSomething = doSomething;

public void Bar()

It appears that with TypeMock we don’t have to have this abstraction
if we wish to test the DoSomething method is being called inside Bar;
we can just new up our IDoSomething implementation. This lead to a
wave of comments from people saying that this abstraction isn’t there
just for enabling testability, but quite simply functions as a better code design (ie dependency injection).

However, the main difference between the two platform, as it was put by Joshua Flanagan and Scott Bellware lays in the fact that all classes in ruby are open hence support for testability is provided in ruby within the language itself.

I was thinking about this question, trying to find another way to express  DI in c#, whilst attempting to reduce the superfluous abstractions, when the usage of delegations came to my mind, and I offered this solution:

public class Foo


 Baz _baz;

 public Foo(Baz baz){

 _baz = baz;


 public void Bar()





public class Baz


 private Action _doSomething = () => Console.Write("doing something");

 //or throw NotImplemented...

 public Baz(){}

 public Baz (Action doSomething)


 _doSomething = doSomething;


 public void DoSomething(){




And this is exactly where I’ve learned the most valuable lesson- Scott Bellware kindly enough provided a better solution to mine, in which he simply took out the redundant and, well, superfluous abstraction that was the Baz class and put the Action delegate directly in Foo. As obvious and trivial as it may seem, with a bit of refactoring or even stopping myself and taking the time to reflect a bit more on my solution I would have arrived to the same conclusion- no brain surgery. However, what I could see is that I still came up first with this solution rather than the other one. Even if I would have thought of the other only a minute after, still my mind reacted in this knee-jerk manner and spat out first this way of doing things. Bellware described it better:

“With the advent of callable objects in C# (Action, Predicate, and friends), command patterns can also be implemented using callable objects. However, there are years of habit-forming class-oriented implementation of command patterns backed up in idiomatic C#, and often command patterns fall back to the class-oriented habit even though there are now callable object alternatives.”

My mind is driven by the way I’m used to think in the language I use each and every day (c#) and in order to be able to break these language boundaries I will need to learn a new language, at least to be able to have different perspectives on issues I face on daily basis as a developer.

This fascinating nytimes article discusses the way our mother tongue may shape our way of thinking. One of the most example the article brings is that of ‘geographical languages’, where directions are given only by geographical coordinates (north, south…). The concept of behind, infront etc’ do not exist. The side-effect of speaking such a language can be quite far reaching- when put in a complete strange and unknown environment, geo-language speakers may lose their sense of orientation completely.

Learning new languages can help us get a new perspective on how we see things, how we perceive our surrounding and how we understand our reality. Sounds like a pretty cool thing to me 🙂

Read more: On Design and Testability- Derick Bailey


What can TDD do for your SRP?

June 4, 2010

A while ago I had the opportunity to do an MVC pagination kata, which proved to be a real educational and inspirational experience.

One of the bits I had written was a class that created the pagination part as an html string, Pager.ToString(), using a StringBuilder it went through a chain of condition and added some parts accordingly. for example I created a page number link for certain condition, or added the first, previous, next and last page links. These became methods inside my Pager class, so that my ToString() method won’t get too big. For example:

private void GetPageLink(int page)
 string url = _linkProvider.GetCurrentLinkWithPageQuery(page);
_builder.Append("<a class=\"pageLink\" href=\"" + url + "\" >" + page + "</a>");

Now came the unit test trying to see whether the StringBuilder was called for each bit that was supposed to be added to our pager. Then, having my mind set to think Mocking-wise, I told myself if I get an interface to replace all these private “builder” methods, my code would become a lot more testable:

public interface IPagerBuilder
 void AddLinkToLast();
 void AddLinkToNext();
 void SetPageNumberLink(int i);
 void AddLinkToPrev();
 void AddLinkToFirst();
 void SetPageLocationTitle(int pageIndex, int pageCount);
 string Build();

And my tests like so (for example):

 public void should_have_next_and_last_links()
 paginatedList.Stub(l => l.IsPageCountLessThanRange).Return(false);
 paginatedList.PageIndex = 2;
 paginatedList.Stub(l => l.IsWithinStartingRange).Return(false);
 paginatedList.Stub(l => l.PageCount).Return(5);


 pagerBuilder.AssertWasCalled(b => b.AddLinkToLast());

But hang on, what’s been happening here was quite simply a separation of concerns, my pager class is now responsible for building my pager according to the conditions:

public override string ToString()
 int halfRange = _paginatedList.Range / 2;

 _pagerBuilder.SetPageLocationTitle(_paginatedList.PageIndex, _paginatedList.PageCount);

 if (_paginatedList.IsPageCountLessThanRange)
 for (int i = 1; i <= _paginatedList.PageCount; i++)
 if (_paginatedList.PageIndex > 1)

 if (_paginatedList.IsWithinStartingRange)
 for (int i = 1; i <= _paginatedList.Range; i++)
 else if (_paginatedList.IsWithinEndRange)
 int startPage = (_paginatedList.PageCount - _paginatedList.Range) + 1;
 for (int i = startPage; i <= _paginatedList.PageCount; i++)
 int startPage = _paginatedList.PageIndex - halfRange;
 for (int i = startPage; i < startPage + _paginatedList.Range; i++)

 if (_paginatedList.PageIndex < _paginatedList.PageCount)

 return _pagerBuilder.Build();

And the PagerBuilder class is a simple strategy that adds up html strings to a one big happy html string pager, without having to know a thing about when to add this or that bit, why and in what order. Did anyone say Single Responsibility Principal?

Funny thing is, a week after a colleague of mine came to me with the following question: He had a method in a service class that was validating some input from a view, only he had to use some repositories, and he asked me how could he test it. Needless to say, the answer here was a validator interface…

Composition vs Inheritance vs High Cohesion

April 25, 2010

A couple of months ago Chad Myers has posted a great post about the importance of using composition and its advantages over inheritance, in which he makes the case for (amongst others) using IoC container in order to minimize inheritance. He ends the post by saying that :

Favoring object composition over class inheritance helps you keep each class encapsulated and focused on one task. Your classes and class hierarchies will remain small and will be less likely to grow into unmanageable monsters.

Now, the point I wanted to make is that the key to his post, or in other words to clean, small, easily maintained classes that would respect the single responsibility principle, would be found in the sentence just before the highlighted one- “object composition […] helps you keep each class encapsulated”.

The project that we’re currently working on uses StructureMap as IoC container (and just for the record, not a day passes without me saying thanks to Jebus and Jeremy for providing us with StructureMap! ). The orders we’ve received from our project manager at the beginning of the project were very clear: each controller should depend on one service only, while services should remain as small as possible. Soon after our project manager was high-jacked to other projects and we were left on our own. Now, even though I understood very well what he meant by “don’t let your service to grow too big”, and remembered him showing me a service class from his preceding project that was more than a thousand lines long, I still struggle up to this day with services I’ve written myself, trying to find the time to refactor/split them into several different services. So where did it all go wrong?

So, yes, object composition indeed helps you, but it won’t do the job for you obviously. Personally, from what my experience have taught me, I could have really got it right the first time had I understood and grasped the idea of high cohesion. The first example that pops to my mind is a controller I’ve written for the creation of one of our bigger entities. I used composition when I’ve written the entity itself, seeing that it was too big and that it demanded a wizard-like user interface, so that each wizard step was encapsulated into an entity. However, I have failed to split the service into several ones, thus ended up little by little with an ever growing, massive class with far too many dependencies. Thing is, in this case the separation was needed in every layer,  so that my controller and the service dragged one another- since I had one controller only to take care of the entire creation process, and the controller was dependant on one service only, I found myself with a service class that is a nightmare to maintain.

From Wikipedia:

cohesion is a measure of how strongly-related or focused the responsibilities of a single module are. […] If the methods that serve the given class tend to be similar in many aspects, then the class is said to have high cohesion. In a highly-cohesive system, code readability and the likelihood of reuse is increased, while complexity is kept manageable.

Cohesion is decreased if:[…]

  • Methods carry out many varied activities

Clearly, the whole creation process of this complex entity wasn’t supposed to  be contained in a sole controller/service.

Failing to understand all that, I managed to bloat one of the layers of our application, while using DI. Some of our services more than 15 dependencies in their constructors!

On top of that, using MSMVC’s magic strings everywhere made the refactoring and splitting of controllers (and thus of services) an extremely difficult task. This is a case where the advantage of FubuMVC over MSMVC is very clear 🙂

On SRP and staying DRY

April 4, 2010

A couple of weeks ago Chad Myers posted a message on the Fubu group explaining the difference between Fubu and MS MVC. This was definitely an Eureka moment for me- suddenly SRP made sense to me and it all clicked into place. In his message, Chad says:

Front Controller is also
about composing the response.  Sometimes the view needs more information
than what is relevant to the “meat” of the request (i.e. displaying the
login page may involve displaying advertisements or notifications, etc that
are not necessarily the responsibility of the Login action).

The first thing that popped into my mind was the parent controller Uber class we’ve got in the project I’m working on currently. In it we deal with security and authentication issues, we deal with requests for downloading help files for each and every page in the web site, we deal with maintenance scenarios when the site would need to be down and so on. Needless to say, the number of ifs we’ve got there is starting to get rather unhealthy and the thought of making any changes to any of these responsibilities/logics makes me shudder; with fubu, we could have had a Behaviour for each concern/responsibility. Although this might be a rather extreme example of the Single Responsibility Principle (1 method – 1 responsibility), it is usually clear cut examples that make you grasp the idea fully and understand what were you doing wrong all that time.

From what I’ve experienced up until now, the first sign that makes me look for SRP violations is a forced application of the DRY principle, attempting to mutualise code/logic that seems to be similar and treating the same sort of a scenario. A great example for that scenario was a little feature I had to add a week ago, in which I was supposed to allow the users to subscribe people, while creating their program. We already had a very similar feature that allows the users of the application to subscribe people on their program after the latter has been created. My colleague thought we could simply reuse the views and actions we already created. That was a good enough sign for me to get some more explanations about the process of subscribing someone to your program while creating it, and needless to say it turned out that “it would be exactly the same thing, only…” and this ‘but’ made changes to some data access logic we had and the way we use NHibernate to get this data. We ended up separating these two scenarios and the best thing is that we’ve gained a lot in doing so in terms of maintainability 🙂