I've joined the Anti-IF Campaign

Saturday, 2 May 2009

Grokking the SRP

I've been doing a lot of thinking about the single responsibility principle recently. It is one of the many excellent things I've learned from reading Clean Code (there's that book again, I promise to stop namechecking it soon). Basically, the single responsibility principle asserts that classes should have only one reason to change.

One bit that I really like about it is that definition of responsibility: a reason to change. Defining it thus, in terms of the effects, immediately suggests some of the benefits that are available to adherents to the SRP. Individual changes become localised to specific areas of a system, not strewn out across numerous modules. This means that making changes becomes easier and the risk of introducing problems when making those changes is decreased. It also has the effect of making code easier to read, because each module in the system will be focused on just one area.

Another good aspect of the SRP is that it provides an objective test of whether a class is too big. Rather than relying on some abstract property such as the number of lines of code it has, it suggests instead ways to verify that even very short classes are not doing too much. For instance, if some member variables are used only by a subset of methods in a class, that might be a reasonable pointer to a smaller class that is stuck inside waiting to be released.

And the SRP applies to methods too. It is commonly accepted that good functions do one thing, at one level of abstraction. Conceptually, this just seems like the SRP at the function level to me.

My realisation of the fundamental truth encapsulated by the SRP has already led to one significant set of refactorings in one of my side-projects: the extraction of all exception-throwing code out to dedicated exception-throwing classes. All told, the process took a couple of weeks of my spare time, but it was worthwhile. The resulting code was both shorter and eminently more understandable. Looking forward, I feel more confident as a developer, having the SRP in my armoury.

0 comments:

Post a Comment