2. What are SOLID PRINCIPLES
SOLID is a mnemonic acronym for five design principles intended to
make software designs more understandable, flexible, and
maintainable. The principles are a subset of many principles promoted
by American software engineer and instructor Robert C. Martin ~
wikipedia
4. “A class should have one, and
only one, reason to change.”
● Classes with multiple responsibilities have more reasons to change,
making them more complex and harder to maintain.
● If your class implements multiple responsibilities, they are no longer
independent of each other.
5. ADVANTAGES
● Testing – A class with one responsibility will have far fewer test cases.
● Loose coupling – Less functionality in a single class will have fewer dependencies.
● Organization – Smaller, well-organized classes are easier to search than
monolithic ones
6. Example:
The Employee class is refactored into distinct classes for salary
calculation, salary slip printing, and data saving to adhere to SRP.
Original Class (Not following SRP):
9. “Classes should be
open for extension and
closed to
modification”
● This means that a class should be
extendable without modifying the class
itself.
12. “Every subclass or derived
class should be substitutable
for their base or parent class.”
13. Example:
When a SalaryPrinterService is designed to work with objects of type Employee, it
should also work with objects of derived classes such as ContractEmployee without any
issues.
15. “A class should never be
forced to implement an
interface that it doesn’t
use, or class shouldn’t
be forced to depend on
methods they do not
use.”
16. Example:
The ElectricCar class implementing a Car interface with a
turnOnEngine method violates the Interface Segregation
Principle, which advises against forcing classes to implement
irrelevant methods.
Car Interface:
19. “Entities must depend on
abstractions, not on concretions.”
● It states that the high-level module must not depend on the low-
level module, but they should depend on abstractions.
20. Example:
The EmployeePersistence class should rely on the IStorage interface rather than concrete
LocalStorage or DBStorage classes for data storage. This ensures flexibility in changing storage
types without modifying the underlying persistence logic.
Interface for storage abstraction:
23. CONCLUSION
The broad goal of the SOLID principles is to
● reduce dependencies so that engineers change one area of software
without impacting others.
● lead to better code for readability, maintainability, design patterns,
and testability.
● Lays the foundation for implementation of Clean Architecture