SOLID Principles
- Introduced by Robert C.Martin, known as Uncle Bob
- A set of principles that must be followed to develop flexible, maintainable, and scalable software systems
- Helps in reducing 'Tight Coupling': A group of classes is highly dependent on one another.
- Loosely coupled classes minimize code changes, making code more reusable, maintainable, and flexible.
Single Responsibility Principle
- One class = One responsibility
- One class = One reason to change
Problem: The
Program
class violates the SRP as it handles three separate responsibilities: Main()
, CalculateArea()
, and Print()
.Rectification:
Open-Closed Principle
Class must open for extension, but closed for modification
CalculateArea()
and Print()
requires passing a rectangle parameter, but the current design does not allow it.Rectification: Therefore, we need to extend the
CalculateArea
and Printer
classes without modifying their existing methods.Liskov Substitution Principle
All the parent class methods must apply to the child class.
Problem: The Square
class is forced to inherit from Rectangle
. However, this requires explicitly defining the rectangle’s length and breadth in the Square
class, even though it’s unnecessary.
Rectification:
Problem: Cube is forced to implement
GetArea()
.