SOLID principles
SOLID principles are the 5 principles of object oriented class design. Design principles encourage us to create more maintainable, understandable, and flexible software. Consequently, as our applications grow in size, we can reduce their complexity and save ourselves a lot of headaches further down the road!
1. Single responsibility principle
This principle states that a class should only have one responsibility. Furthermore, it should only have one reason to change.
How it is helpful to build better software:
- Testing — As class has only on responsibility there would be fewer test cases.
- Organisation — It is easy to read and understand a simple code.
- Lower coupling — There will be a lower dependancy
2. Open-closed principle
A class should be open for extension and close for modification. We should not modify existing code to generate new bugs.
Using inheritance or interfaces that allow polymorphic substitutions is a common way to comply with this principle
3. Liskov substitution principle
This principle states that subclasses should be substitutable for their base classes. This principle ensures that any class that is the child of a parent class should be usable in place of its parent without any unexpected behaviour.
Get Webencyclop’s stories in your inbox
Join Medium for free to get updates from this writer.
Example: A farmer’s son should inherit farming skills from his father and should be able to replace his father if needed. If the son wants to become a farmer then he can replace his father.
Similarly, B is a child of A so object of A should be replaced by B without altering properties of a program.
Explaining in an example, square class is child of rectangle. But we can’t replace square in place of rectangle. Which is not correct so it’s violating the Liskov principle.
4. Interface segregation principle
This principle applies to Interface similar to single-responsibility principle for class.
For different different purposes we should write separate interfaces rather creating only one general interface.
Real-life example: veg and non-veg menu should be different in Menu card. Not a veg and non-veg dishes mention on only one page.
5. Dependancy inversion principle
High level classes should not be depend on low level classes. This is useful to remove dependancy. Classes should not be tightly coupled.
How to achieve this? → Using abstraction we can achieve dependancy inversion principle.
Real-life example — TV remote should not depend on battery type. Any brand batteries should work with remote.







