The SOLID principles are a set of five design principles in software development intended to make software designs more understandable, flexible, and maintainable.
These principles were introduced by Robert C. Martin (also known as Uncle Bob) to guide developers in creating better software architecture.
We will look each of these principles one by one:
Single Responsibility Principle (SRP)
It states that
A class should have one and only one reason to change
Example:
If we carefully observe in the above Employee class, we are doing two things i.e storing employee and calculating pay which defies SRF.
The Solution for the above problem is just create two classes like below:
Open Closed Principle (OCP):
It states that
Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification
Example:
Let us consider below class to calculate penal fee based on lender:
Suppose if we want to add another lender, we need to modify this class which is not best practice and defies OCP.
Solution for the above problem is:
Liskov Substitution Principle (LSP)
It states that
Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program
In other words,
Inheritance hierarchies such that derived classes must be completely substitutable for their base classes
Example:
In the above code, we have seen it clearly violates LSP.
Solution for the above problem is:
Interface Segregation Principle
It states that
Clients shouldn’t be forced to depend on methods they do not use.
Solution:
Dependency Inversion Principle
It states that
High-level module must not depend on the low-level module, but they should depend on abstractions.
Solution:
Advantages
- Maintainability
- Flexibility and Extensibility
- Readability and Understanding
- Quality Software
Happy coding!
Feel free like this blog and subscribe for more tech blogs.
Feel free to buy me a coffee: https://ko-fi.com/repanareddysekhar
Top comments (0)