“SOLID” with a Simple Example
“SOLID” are five basic principles that help to create good software architecture. “SOLID” is an acronym.
- S – SRP (Single responsibility principle)
- O – OCP (Open closed principle)
- L – LSP (Liskov substitution principle)
- I – ISP (Interface segregation principle)
- D – DIP (Dependency inversion principle)
Single Responsibility Principle (SRP)
SRP says that classes or modules should have only one responsibility and not multiple.
Problem
We can notice that in below code, the Add method has too many responsibilities, where it will have an add method to DB and error handling logic. This violates the single responsibility principle.
Solution
Abstracting functionality of error logging so we no longer violate the single responisbility principle
Open Closed Principle (OCP)
OCP says that software entities (classed, modules, methods, etc) should be open for extensions, but closed for modification.
Problem
We can notice in below code that it is violating the Open Closed Principle, because if we need to add another company (like big basket) we need to modify the existing code in the switch statement
Solution
By creating inheritance, we make it easy to modify by adding a derived class without touching the existing class
Liskov substitution principle (LSP)
LSP says that a parent class should be able to refer child objects seamlessly during runtime polymorphism
Problem
We can notice in the below code, for COD (Cash on deliver) transaction there is no need to check the balanace method/feature and deduct an amount method/feature, but the client is still using it.
Solution
As a COD (Cash on deliver) transaction is only needed to do a transaction, there’s no need to check the balance method/feature and deduct the amount method/feature. We can use the interface and implement it based on the scenario.
Interface segragation principle (ISP)
ISP says show only the methods to the client which they need, i.e., no client should be forced to depend on methods they do not use.
Problem
We can notice in below code, as we add more functionalities (i.e. read method) all the client should use is read method, if it’s not required.
Solution
By creating another interface and extending from it, we can avoid violating the above scenario.
Dependency inversion principle (DIP)
DIP says that high-level modules should not depend on low-level modules, but rather should depend on abstraction.
Problem
We can notice that in the below code, in case if we want to change FileLogger to EmailLogger method/feature, we have to modify it in the Customer class, thus it was violating this principle.
Solution
By injecting any dependencies of a class through the class constructor as an input parameter.
Summary
In this article, we have learned simple examples of the SOLID principles.