SOLID Principles


  1. Introduced by Robert C.Martin, known as Uncle Bob

  2. A set of principles that must be followed to develop flexible, maintainable, and scalable software systems

  3. Helps in reducing 'Tight Coupling': A group of classes is highly dependent on one another.

  4. 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


Problem:
 When creating a new shape, such as a rectangle, calling 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:


Interface Segregation Principle

Don’t force classes to implement methods they don’t need.


Problem: Cube is forced to implement GetArea().

Rectification:

Dependency Inversion Principle

  1. States that a high-level class must not depend upon a lower-level class.
  2. Both Classes depend on abstractions(interfaces or abstract classes), not concrete classes.
  3. Use Dependency Injection (in Design Pattern)