In object-oriented programming, there are five basic principles (SOLID) that, properly applied, make the difference between a good and a bad design. The difference between an application that is easy to maintain and one that is not. The difference between a good developer and a bad one.
- Single Responsibility Principle
- Open/Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
SINGLE RESPONSIBILITY PRINCIPLE
We’re going to start with the first one, the Single Responsibility Principle (SRP) that is defined by Robert C. Martin in his book “Agile Software Development, Principles, Patterns, and Practices”. The principle is actually a very simple concept to explain, however, difficult to implement. As its name suggests, it implies that a class or module must have a unique responsibility.
Within the context of the Single Responsibility Principle, responsibility is defined as a reason to change. That is why I consider the phrase of Robert C. Martin as a perfect definition of what is the SRP:
“A class should have only one reason to change.”
By following this principle, you make sure that your class or module has high cohesion, which means that your class does not more than what it should do. In short, one unique reason to change. If on the contrary, you build a class with more than one responsibility, what you’re doing is that you’re engaging these responsibilities. This leads to a design that is fragile and difficult to maintain, with all that that entails.
EXAMPLE
In this simple example, you can see a rectangle class that has two methods; Area () & Draw ().
- Area () has the responsibility to return the area of a rectangle
- Draw () has the responsibility to draw the rectangle itself
In this design, it can be seen that, if there are changes in the GUI, we must modify the Rectangle class, then we are obliged to test again the other application that attacks the same class. The solution to this problem is to divide the class in two, so that each class has a unique responsibility. One will be responsible for calculating and another one for painting:
It’s important to keep in mind that this principle leads to many other nuances and concepts, and not only those that fall within SOLID, but others that should be known and able to apply to to get an application with a solid design.