Design Patterns and Coding Principles
SOLID Design Principles
The term “SOLID” in software engineering refers to a group of five design principles that are meant to improve the readability, flexibility, and maintainability of object-oriented designs.
The SOLID design principle includes the following five principles:
- Single-responsibility principle
- Open-closed principle
- Liskov substitution principle
- Interface segregation principle
- Dependency inversion principle
American software engineer and instructor Robert C. Martin (popularly known as Uncle Bob) introduced these design principles in his 2000 paper Design Principles and Design Patterns. Michael Feathers later transformed these principles into an acronym.
We will examine each of them to learn how these principles can aid in the creation of software that is well-designed.
Single-Responsibility Principle (SRP)
Robert C. Martin, the originator of this principle, put it this way: “A class should have only one reason to change.” It means that every module, class, or method should only have one (single) responsibility or job.
|SOLID - Single-Reponsibility Principle.|
Uncle Bob defines responsibility as a reason to change, and he suggests breaking down components such as classes, modules, and methods until each has a single reason to change.
Why do we need to do this, and what benefits will be gained by breaking a component into subcomponents where each must have a single responsibility? The idea is that each class or method is responsible for a single part of the product’s functionality, i.e., each class or method does just one job. This keeps the design as simple as possible and makes it easier and less disruptive to make changes in the future. Furthermore, it improves the quality of the codebase in general.
What if our class has multiple responsibilities to fulfill? A class with multiple responsibilities has a higher chance of having bugs since altering one of those responsibilities might have unintended effects (side-effects) on the others.
Having said that, utilising SRP principle makes code easier to maintain and test.