SRP says that classes or modules should have only one responsibility and not multiple.
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.
Abstracting functionality of error logging so we no longer violate the single responisbility principle
OCP says that software entities (classed, modules, methods, etc) should be open for extensions, but closed for modification.
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
By creating inheritance, we make it easy to modify by adding a derived class without touching the existing class
LSP says that a parent class should be able to refer child objects seamlessly during runtime polymorphism
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.
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.
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.
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.
By creating another interface and extending from it, we can avoid violating the above scenario.
DIP says that high-level modules should not depend on low-level modules, but rather should depend on abstraction.
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.
By injecting any dependencies of a class through the class constructor as an input parameter.
In this article, we have learned simple examples of the SOLID principles.