Table of contents:
Part 2 – SRP (this post)
In the previous post I introduced the SOLID principles and their relation to TDD in general. And as promised, I’m diving into each of these principles and explain their relationships with TDD.
The first principle, which I’ll be talking about in this post, is the Single Responsibility Principle or SRP in short.
SRP is the principle that is easiest to understand, but not as easy to get right. In short, as its name implies, it means that a class should have only one responsibility, and not intermix responsibilities that are separable. It implies that classes should be kept as simple as possible, and anything that is not part of the class’s main responsibility should be the responsibility of some other class. In fact, this principle applies even more to interfaces than to classes. SRP implies cohesion and lack of coupling.
SRP can bee looked at as the basic principle that the rest of the principles (mainly OCP) only clarify for more specific circumstances.
Sometimes when you’re looking at a class it’s very clear that it violates the SRP. But often the line is not so clear, and only when the code evolves and you’re refactoring, then you notice the multiple responsibilities. Clearly TDD provides you with the safety net of tests while you’re refactoring your code. But it’s not the only way that TDD helps you adhere to the Single Responsibility Principle. If your class annexes additional responsibilities, your tests become complex and cumbersome. But in TDD, because you strive to write the simplest tests first then you’re more likely to write the tests for a new class in the first place rather than a complex test for an existing one.