S.O.L.I.D


SOLID is an acronym for the first five object-oriented design (OOD) principles.

  • S – Single-Responsiblity Principle
  • O – Open-Closed Principle
  • L – Liskov Substitution Principle
  • I – Interface Segregation Principle
  • D – Dependency Inversion Principle

Single-Responsibility Principle

A class should have one and only one reason to change, meaning that a class should have only one job.

This means that every class, or similar structure, in your code should have only one job to do. Everything in that class should be related to a single purpose. It does not mean that your classes should only contain one method or property. There may be many members as long as they relate to single responsibility.

Open-Closed Principle

Objects or entities should be open for extension but closed for modification.

We need to design our module/class in such a way that the new functionality can be added only when new requirements are generated. “Closed for modification” means we have already developed a class and it has gone through unit testing. We should then not alter it until we find bugs.

For example:

We define an abstract class called ‘Shape’.

public abstract class Shape { public abstract double Area(); }

We create a ‘Rectangle’ class that inherits from ‘Shape’.

public class Rectangle: Shape  
{  
   public double Height {get;set;}  
   public double Width {get;set;}  
   public override double Area()  
   {  
      return Height * Width;  
   }  
}  

Our area calculator uses the abstract class ‘Shape’ rather than concrete class ‘Rectangle’ so that new shapes can be added over time and AreaCalculator will not need to be touched.

public class AreaCalculator
{
   public double TotalArea(Shape[] arrShapes)  
   {  
      double area=0;  
      foreach(var objShape in arrShapes)  
      {  
         area += objShape.Area();  
      }  
      return area;  
   }  
}  

Liskov Substitution Principle

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

Objects of a bas class should be replaceable with objects of its derived classes without breaking the application. In other words, what we want is to have the objects of our derived classes behaving the same way as the objects of our base class.

A client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.

Entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.


One response to “S.O.L.I.D”

Leave a Reply

Your email address will not be published. Required fields are marked *