domingo, 5 de julho de 2015

Single Responsibility Principle

Continuing our line about clean code, let's talk about Single Responsibility Principle, the first of the five SOLID principles.

The Single Responsibility Principle tells us the class must have one responsibility and one reason to change. Again, here's another citation from Robert Martin:

"A class should have one, and only one, reason to change"
Each class must have one responsibility, and it means that this class should do one thing, this way, having one reason to change. Let's analyze the class below and identify the responsabilities it has:

Clearly this class is doing more than one thing. The first one is to make the authentication, the second one is to create the session. In this case, with two responsibilities, this class becomes more complex, hard to test, highly coupled and hard to maintain, probably resulting in bugs.

Let's say the system needs a maintenance on the creation of the session, the details about how to create the session is not related to authentication, the developer must read the class name and understand what it should do exactly, in this case, authenticate a user. If I had the task to make this maintenance, I would find for a class called SessionManager or something like this to make the required changes.

The code below is how I imagine it should be:

Some of the goods of this principle:

  • Code more readable and clean;
  • Code more testable;
  • Less mocks on the tests;
  • Less complexibility;
  • Easy to maintain.


Classes should do one thing, it will make everyone happier, who writes the class, who creates tests and who makes some maintenance on it. Having one responsability on the class, it will avoid many problems and make the project cleaner and easier to maintain.