The Single Responsibility Principle states that a class should only have one reason to change. Another possible title for this design principle would be the Single Reason to Change Principle.

Why is it important for a class to have a single reason to change and what are its benefits? One of the easiest ways to enhance the maintainability of a code base is to have it loosely coupled. In loosely coupled code, a change to one feature does not affect any other functionality. It is the opposite of spaghetti code where everything happens in one big method and changing how one functionality works very likely affects all the other functionality. And to get this loosely coupled code, each feature should be broken up into individual classes. If each class implements only one feature, then it only has one reason to change and when you change that feature you don’t have to worry about it breaking anything else in the code base.

A good example of a violation of the Single Responsibility Principle is having data validation and storage in the same class. Take a look at the code below as an example.

public virtual void Save(User user)
{
  if (string.IsNullOrEmpty(user.Name))
    throw new ValidationException("User name cannot be blank");

  using (var conn = new SqlConnection("connection string"))
  using (var command = conn.CreateCommand())
  {
    command.CommandText = "INSERT INTO USERS (Name) VALUES (:name)";
    command.Parameters.Add(new SqlParameter(":name", user.Name));
    command.ExecuteNonQuery();
  }
}

This code violates the Single Responsibility Principle because it performs two tasks: validating the object and persisting the object. These two responsibilities are orthogonal to each other and should be separated out to two classes since neither one affects the other.

Now that I have explained this design pattern, I want to give my opinion on its usage. I believe this principle is good to follow when designing applications but I don’t think it should followed to a T. I say this because I see some people take it too far. For instance, take for example the interface below.

public interface Modem
{
  public void Dial(string phoneNumber);
  public void Hangup();
  public void Send(string message);
  public string Receive();
}

Some would say the methods on this interface need separated out into 2 interfaces, one that takes care of the connection (Dial and Hangup) and another that takes care of the communication (Send and Receive). Personally I disagree. Yes, I can see how some could consider there being 2 responsibilities in this class, but then what is to keep the interface from being broken up into 4 interfaces, one for each method, because I could also see how Dial is a distinct responsibility from Hangup and Send is a different responsibility than Receive.

As far as implementing the Single Responsibility Principle, I personally advocate that there needs to be a sliding scale on how fine tuned the responsibilities are split out.

Before I expound on my position further, I need to introduce a term called responsibility group. A responsibility group is a set of responsibilities that correlate to each other in one way or another. The size of a responsibility group can be anywhere from large to small. The smaller the responsibility group, the more closely each responsibility correlates to each other, and the larger the group, the more loosely the responsibilities correlate to each other.

The smaller the application, the larger the responsibility group should be, and the larger the application, the smaller the responsibility group should be. The graph below shows a visual representation of what I’m talking about.

ApplicationResponsibility

I advocate this view as a result of my own experience. I volunteer my time at a non-profit organization where I have developed quite a few applications to help automate some of their administrative tasks. Many of these applications are quite small with less than 100 lines of written code. In these applications do I separate out the validation logic from the persistent logic? No, it’s not worth it. If I did I would very likely have more classes than I did lines of code. However, in my open source project (Linq to Excel) I have much smaller responsibility groups since it’s a larger project with many features.

One of the arguments for using this principle is making the code easier to maintain and add enhancements. But with small applications that serve a single specific purpose, it’s quite unlikely that they will change. And even if they do change and enhancements are added, the Single Responsibility Principle with smaller responsibility groups can be implemented by refactoring the code when the enhancements are added.

These are my thoughts and 2 cents worth on the Single Responsibility Principle. I know I do not follow the main stream of thought for this principle so I would love to receive feedback on my ideas on this principle. What is your experience with using this principle?

 | Posted by admin | Categories: Uncategorized |

Last week was the first time I used the jQuery javascript library and I must say I’m impressed. It has one of the simplest APIs that I have used which made learning how to use it quick and easy. In fact, I was able to write a custom plugin for it within a couple hours!

I would like to cover the business problem I had and how I used jQuery to solve it. One of the internal web sites at my company has a user rights management page where an administrator can control the individual rights on the site for each user. This page has a drop down list of all the employees which is used to give rights to a specific employee. The problem was the drop down list was not alphabetized and it contained over 1,400 employee names to choose from! It felt like finding a needle in a haystack every time a new employee was given rights.

The root cause of the issue was the use of a hacked together database view that returned the list of employees ordered by their full name. Database views are not supposed to have order by commands, but this one did and the website was expecting the view to provide the ordering. However, the view was not returning the employees as properly ordered. After some research it was found that the database optimizer figured that bypassing the view and using the data directly from the table was more efficient than going through the view, which meant that any code using the view would receive an unordered list of employees.

Once that was figured out I was able to add an order by to the sql command and the drop down list was now ordered correctly.

However, there is an acronym we often use at work as our motto: MISL (pronounced missile)

Make
It
Suck
Less

And only alphabetizing the list did not Make It Suck Less enough for me. It was still a pain the neck to scroll through the 1400 employee names in the drop down list.

My solution was to use jQuery to replace the drop down list with an auto complete text box that had the same value as the drop down list.

After finding an auto complete plugin for jQuery I was ready to implement my solution.

The first thing I did was hide the drop down list and add an input text box after it

$dropDown = $("#EmployeeDropDownList");
$dropDown.hide()
   .after("<input type='text' />");
var $autoCompleteTextBox = $dropDown.next();

I then retrieve the array of employee names from the drop down list and pass it as an argument to the autocomplete plugin

var dropDownItems = [];
$dropDown.find("option").each(function() {
   dropDownItems.push($(this).text());
});

$autoCompleteTextBox.autocomplete(dropDownItems);

I then subscribe to the blur event on the new auto complete text box to synchronize the selected value on the hidden drop down list with the value in the auto complete text box

$autoCompleteTextBox.blur(function() {
   var textBoxValue = $autoCompleteTextBox.val();
   $dropDown.val(textBoxValue).attr("selected", "selected");
});

And finally I validate the value in the text box is the selected value in the drop down list when the submit button is clicked.

$("#SubmitButton").click(function(e) {
   var textBoxValue = $autoCompleteTextBox.val();
   var selectedValue = $dropDown.find("option:selected").text();
   if (textBoxValue != selectedValue)
   {
      alert(textBoxValue + " is an invalid selection");
      e.preventDefault();
   }
});

I am still pretty amazed by how simple and succinct jQuery is. It was actually really fun to learn and play around with and I look forward to using jQuery in the future.

 | Posted by admin | Categories: Uncategorized |

Learning by teaching

25 November 2009

It’s been over 3 years now that I have been out of college and have done any intense studying. And by intense studying I mean studying a subject to a point that I intimately understand it and could teach it. As a software developer I am constantly reading development blogs and magazines and learning new ideas and techniques, but I rarely study a new feature or enhancement to the point that I understand it. I more so study to the point that I know how to use the new feature but I don’t understand the inner workings of the feature. Take for example dynamic objects in the .Net framework 4.0. I’ve read a couple blog articles and listened to a recorded talk from PDC and now know how to implement a basic dynamic classes. I know that the new DLR allows for the use of dynamic objects but other than that I don’t know much more about dynamic objects. How much slower are they than static objects? How do you cache methods in dynamic classes?

I am seeing things from a birds eye view but I want to start seeing things up close and truly understand subjects I am studying. It’s often been said that the best way to learn something is to teach it. And one way to teach is to write blog posts, so I am going to write blog posts on the subjects that I am currently studying to help me more fully understand.

So what subject am I going to start studying? Software design principles. It’s something not taught in school and yet is what separates the good coders from the bad.

Here’s to studying to learn…

 | Posted by admin | Categories: Uncategorized |

Joel Spolsky recently published a post entitled The Duct Tape Programmer. I must say that there are some points Joel makes that I strongly disagree with. I hate the attitude that getting the application done as quickly as possible is all that matters. The only situation where I would even remotely consider this is for an app that will only be used once. Why? because an app that is used once doesn’t need to be maintained, and duct tape code that is written to ship the software as quickly as possible is horrible to maintain. So sure, you might be able to ship the app quicker and produce some extra revenue because of it, but you will lose revenue in the long run as the maintenance cost will skyrocket because it will be hard to maintain and if any enhancements are added then most likely large amounts of code will need to be rewritten.

Another sentence from the post that irritates me is the following: “One principle duct tape programmers understand well is that any kind of coding technique that’s even slightly complicated is going to doom your project.” Really? So we should all code like we did in college and never get better? There’s a reason for the complication in some code… it’s because it makes it easier. Easier to maintain and easier to add enhancements. So what if it’s complicated. Learn it. I’m not going to write simple software just so the average joe can understand it. I’m going to write software that’s easy to maintain and easy to add enhancements, and that often means the code can become somewhat complicated.

Now that I went on my rant, I do think there is some good in Joel’s post. I think some programmers, myself included, like creating huge frameworks that will clean the dishes and do the laundry, but often times it is overkill and not needed. But that should not be an excuse to write half-ass code either.

 | Posted by admin | Categories: Uncategorized |

This past weekend as I was working with Fluent NHibernate, I received an error from NHibernate saying the mapping was incorrect. Since Fluent NHibernate creates the xml mappings, there wasn’t an easy way for me to see what was wrong in the xml mapping. After a little research I figured out how to get Fluent NHibernate to write the xml mappings to a directory. Check out the code below

var mappings = AutoPersistenceModel.MapEntitiesFromAssemblyOf();
mappings.CompileMappings();
mappings.WriteMappingsTo("SomeDirectory");
 | Posted by admin | Categories: Uncategorized |