Archives For January 31, 2013

The Single responsibility principle states that each class should have a single reason to change. There are certainly many ways to deduce if a class has too many responsibilities, most of which actually require you to use your brain! However, a quick-and-dirty way to establish if a class has too many responsibilities is simply to look at the list of using statements at the top of the file (imports in Java and Visual Basic.NET). If you open the source file in your IDE of choice and the list of usings/imports fills your entire view, the class is likely to have a lot of reasons to change.

Here is what the list of using-directives in one of our classes looked like a few months ago:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Text.RegularExpressions;

The likelihood that a class like this was developed using test-driven development seems slim (and indeed, it was not).

I don’t really believe that we can set a strict “maximum” number of using directives to allow, but probably anything more than six or seven should serve as an indication that perhaps the class in question could do with some refactoring. Perhaps we can use the number of usings/imports as a metric describing code complexity, albeit a very blunt one.