Table of Contents
- Single Responsibility Principle
- Open/Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
SINGLE RESPONSIBILITY PRINCIPLEWe’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 Single Responsibility Pinciple:
“A class should have only one reason to change.”By following the single responsibility 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.
EXAMPLEIn 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