Single Responsibility Principle (SRP)
SOLID Principles are a set of object-oriented design principles that aid in the removal of code smells.
The five SOLID Principles are:
Single Responsibility Principle
Open-Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
The Single Responsibility Principle states:
A class should have only one reason to change.
The Single Responsibility Principle (SRP) is perhaps the easiest principle to understand conceptually, but tends to be the most often violated. Because of this, let’s take a look at how to determine what responsibilities a class has.
1. Can you describe the behaviors of the class without using “and” or any other conjunction?
During my first code review of my Tic Tac Toe game, I was asked to explain what one of my classes was doing. When I began explaining it out loud, it immediately occurred to me that my class had too many responsibilities when I could't describe it without using "and". The interesting thing is that I didn’t realize it while I was actually writing the code.
This proved to be an important lesson for me. It was at this point that I realized the importance of verbalizing out loud what a class is doing. It was also at this point that I determined I would make this a practice of my own from that point on.
Referred to as Rubber Ducking, Andrew Hunt and David Thomas describe this technique in The Pragmatic Programmer with regards to debugging. I’ve found it particularly useful anytime I’m reviewing the code that I’ve written. Force yourself to explain out loud what your class is doing--whether or not there's anyone around for you to explain it to. Doing so will help you spot if your class is doing too much.
2. Do the behaviors of the class relate to the class name?
In order to explain this one, I’d like to show an example from my Tic Tac Toe game:
Here I have a class named GameSequence. At this particular point in development, this class had more than one responsibility. Can you spot it?
The game_over? method violates SRP. I could have spotted this right away based on the fact that determining if the game is over is not a part of determining the game’s sequence. I had already created a TicTacToeBoard class that was responsible for knowing the state of the board. Determining if the game is over is obviously a better fit for that class.
When checking for responsibilities, ask yourself if the behaviors of your class are related to the name of the class. This can be an easy way to spot a SRP violation.
The more often a class needs to change, the more difficult the application will be to maintain. When a class has multiple reasons to change, you’re at risk of having a rigid and fragile application that can break easily when changes are made. Further, having classes with single responsibilities makes it easier for others to understand what’s going on in the application and saves them time when they need to make changes for any reason.