Posted tagged ‘PPP’

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

[Test]
 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);

 pager.ToString();

 pagerBuilder.AssertWasCalled(b=>b.AddLinkToNext());
 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++)
 _pagerBuilder.SetPageNumberLink(i);
 else
 {
 if (_paginatedList.PageIndex > 1)
 {
 _pagerBuilder.AddLinkToFirst();
 _pagerBuilder.AddLinkToPrev();
 }

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

 if (_paginatedList.PageIndex < _paginatedList.PageCount)
 {
 _pagerBuilder.AddLinkToNext();
 _pagerBuilder.AddLinkToLast();
 }
 }

 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 🙂