Wednesday 21 May 2014

Essential Developer Principles #5–The Short and Simple Principle

Last time in my essential developer principles series, I gave my own slightly modified version of the Open Closed Principle, and once again I want to give my own take on one of Uncle Bob’s famous “SOLID” principles.

Single Responsibility?

The “Single Responsibility Principle” states that each class should only have a single reason to change. The basic idea is that each class should do one thing only. As soon as you detect your class is doing two things, then it is time to refactor one of those responsibilities out.

All well and good, but the trouble is that the concept of a “single responsibility” or a “single reason to change” turns out to be quite hard to pin down exactly. In my early days as a computer programmer, my applications would contain files such as “database.c”, “graphics.c” or “comms.c”. This is a nice separation of concerns, but the trouble is it doesn’t go far enough. Those files would quickly grow very long and unwieldy despite arguably having a “single responsibility”.

Nowadays you can encounter classes like “MainForm.cs” or “AdminController.cs”, which again conceptually have one responsibility, but they typically grow larger and larger over the lifetime of the project until they are several thousand lines long.

In fact the number of lines of code is I think the single best indicator of violation of the Single Responsibility Principle. Which is why I wonder whether calling it the “short and simple” principle may have saved us a lot of time debating what exactly constitutes a single “responsibility”.

Short and Simple

So I propose the “short and simple principle” which states that methods should not have more than 20 lines of code, and classes should not have more than 20 methods. Of course, the number 20 is plucked out of the air, but I think its roughly the right order of magnitude. If your method has 30 lines, there’s almost certainly some sub-block that could be extracted into a well-named function. And if your class has 30 methods, it is almost certain that a subset of them can be moved out into some kind of helper class.

Classes that adhere to the “short and simple principle” are easy to code review, and should be straightforward to test. They also have the great benefit that they are small enough to be completely thrown away and re-written in an afternoon if necessary.

Of course, the problem your software solves could be very large and complicated. But complex software can and should be constructed out of simple parts.

Postscript: After writing this I recently stumbled across this great article from Marco Cecconi about why he doesn’t love the Single Responsibility Principle, in which he offers further criticisms of SRP and suggests another alternative.

No comments: