S.O.L.I.D. Priniciple

a design principle intended to make software designs more understandable, flexible and maintainable

S: Single Responsibility Principle (SRP)

A class should only have a single responsibility, that is, only changes to one part of the software’s specification should be able to affect the specification of the class.

The SRP states that "Every software module should have only one reason to change".

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. Our class should not be like a Swiss knife wherein if one of them needs to be changed then the entire tool needs to be altered. 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.

SRP Example
public class UserService  
{
    public void Register(string email, string password) {
        if (!ValidateEmail(email))     
            throw new ValidationException("Email is not an valid email");    
        var user = new User(email, password);   
        SendEmail(new MailMessage("mysite@nowhere.com", email) { 
            Subject="Hello foo" 
        });   
    } 
    
    public virtual bool ValidateEmail(string email) {
        return email.Contains("@");   
    }   
    
    public bool SendEmail(MailMessage message) {
        _smtpClient.Send(message);  
    }  
}

It looks fine, but it is not following SRP. The SendEmail and ValidateEmail methods have nothing to do within the UserService class. Let's refract it.

public class UserService  
{  
   EmailService _emailService;  
   DbContext _dbContext;  
   public UserService(EmailService emailService, DbContext dbContext)  
   {  
      _emailService = emailService;  
      _dbContext = dbContext;  
   }  
   public void Register(string email, string password)  
   {  
      if (!_emailService.ValidateEmail(email))  
         throw new ValidationException("Email is not an email");  
      var user = new User(email, password);  
      _dbContext.Save(user);  
      _emailService.SendEmail(
         new MailMessage("myname@mydomain.com", email) {
         Subject="Hi. How are you!"
      });  
   }  
}

public class EmailService {   
    SmtpClient _smtpClient;   
    
    public EmailService(SmtpClient smtpClient) {
        _smtpClient = smtpClient;   
    }   
    
    public bool virtual ValidateEmail(string email) {
        return email.Contains("@");   
    }  
    
    public bool SendEmail(MailMessage message) {
        _smtpClient.Send(message);   
    }  
}

Example Scenario : An Account class is responsible for managing Current and Saving Account but a CurrentAccount and a SavingAccount classes would be responsible for managing current and saving accounts respectively. Hence both are responsible for single purpose only.

O: Open Closed Principle (OCP)

Software entities should be open for extension, but closed for modification.

The OCP states that "A software module/class is open for extension and closed for modification".

Here "Open for extension" means, 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. As it says, a class should be open for extensions, we can use inheritance to do this

OCP Example

Suppose we have a Rectangle class with the properties Height and Width.

public class Rectangle{  
   public double Height {get;set;}  
   public double Wight {get;set; }  
}

Our app needs the ability to calculate the total area of a collection of Rectangles. Since we already learned the Single Responsibility Principle (SRP), we don't need to put the total area calculation code inside the rectangle. So here I created another class for area calculation.

public double TotalArea(Rectangle[] arrRectangles)  
   {  
      double area;  
      foreach(var objRectangle in arrRectangles)  
      {  
         area += objRectangle.Height * objRectangle.Width;  
      }  
      return area;  
   }  
}   

Hey, we did it. We made our app without violating SRP. No issues for now. But can we extend our app so that it could calculate the area of not only Rectangles but also the area of Circles as well? Now we have an issue with the area calculation issue because the way to do circle area calculation is different. Hmm. Not a big deal. We can change the TotalArea method a bit so that it can accept an array of objects as an argument. We check the object type in the loop and do area calculation based on the object type.

public class Rectangle{  
   public double Height {get;set;}  
   public double Wight {get;set; }  
}C#$  
public class Circle{  
   public double Radius {get;set;}  
}  
public class AreaCalculator  
{  
   public double TotalArea(object[] arrObjects)  
   {  
      double area = 0;  
      Rectangle objRectangle;  
      Circle objCircle;  
      foreach(var obj in arrObjects)  
      {  
         if(obj is Rectangle)  
         {    
            area += obj.Height * obj.Width;  
         }  
         else  
         {  
            objCircle = (Circle)obj;  
            area += objCircle.Radius * objCircle.Radius * Math.PI;  
         }  
      }  
      return area;  
   }  
}   

Wow. We are done with the change. Here we successfully introduced Circle into our app. We can add a Triangle and calculate it's area by adding one more "if" block in the TotalArea method of AreaCalculator. But every time we introduce a new shape we need to alter the TotalArea method. So the AreaCalculator class is not closed for modification. How can we make our design to avoid this situation? Generally, we can do this by referring to abstractions for dependencies, such as interfaces or abstract classes, rather than using concrete classes. Such interfaces can be fixed once developed so the classes that depend upon them can rely upon unchanging abstractions. Functionality can be added by creating new classes that implement the interfaces. So let's refract our code using an interface.

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

Inheriting from Shape, the Rectangle and Circle classes now look like this:

public class Rectangle: Shape  
{  
   public double Height {get;set;}  
   public double Width {get;set;}  
   public override double Area()  
   {  
      return Height * Width;  
   }  
}  
public class Circle: Shape  
{  
   public double Radius {get;set;}  
   public override double Area()  
   {  
      return Radius * Radus * Math.PI;  
   }  
}   

Every shape contains its area with its own way of calculation functionality and our AreaCalculator class will become simpler than before.

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

Now our code is following SRP and OCP both. Whenever you introduce a new shape by deriving from the "Shape" abstract class, you need not change the "AreaCalculator" class.

Example Scenario : A PaymentGateway base class contains all basic payment related properties and methods. This class can be extended by different PaymentGateway classes for different payment gateway vendors to achieve theirs functionalities. Hence it is open for extension but closed for modification.

L: Liskov Substitution Principle (LSP)

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

The LSP states that "You should be able to use any derived class instead of a parent class and have it behave in the same manner without modification".

It ensures that a derived class does not affect the behavior of the parent class, in other words, that a derived class must be substitutable for its base class.

I: Interface Segregation Principle (ISP)

Many client-specific interfaces are better than one general-purpose interface.

The ISP states that "clients should not be forced to implement interfaces they don't use. Instead of one fat interface, many small interfaces are preferred based on groups of methods, each one serving one submodule.".

  • An interface should be more closely related to the code that uses it than code that implements it. So the methods on the interface are defined by which methods the client code needs rather than which methods the class implements. So clients should not be forced to depend upon interfaces that they don't use.

  • Like classes, each interface should have a specific purpose/responsibility (refer to SRP). You shouldn't be forced to implement an interface when your object doesn't share that purpose. The larger the interface, the more likely it includes methods that not all implementers can do. That's the essence of the Interface Segregation Principle. Let's start with an example that breaks the ISP. Suppose we need to build a system for an IT firm that contains roles like TeamLead and Programmer where TeamLead divides a huge task into smaller tasks and assigns them to his/her programmers or can directly work on them.

ISP Example

Based on specifications, we need to create an interface and a TeamLead class to implement it.

public Interface ILead  
{  
   void CreateSubTask();  
   void AssginTask();  
   void WorkOnTask();  
}  
public class TeamLead : ILead  
{  
   public void AssignTask()  
   {  
      //Code to assign a task.  
   }  
   public void CreateSubTask()  
   {  
      //Code to create a sub task  
   }  
   public void WorkOnTask()  
   {  
      //Code to implement perform assigned task.  
   }  
}  

OK. Now, later another role like Manager, who assigns tasks to TeamLead and will not work on the tasks, is introduced into the system. We Can't directly implement an ILead interface in the Manager class, like the following:

public class Manager: ILead  
{  
   public void AssignTask()  
   {  
      //Code to assign a task.  
   }  
   public void CreateSubTask()  
   {  
      //Code to create a sub task.  
   }  
   public void WorkOnTask()  
   {  
      throw new Exception("Manager can't work on Task");  
   }  
}  

Since the Manager can't work on a task and at the same time no one can assign tasks to the Manager, this WorkOnTask() should not be in the Manager class. But we are implementing this class from the ILead interface, we need to provide a concrete Method. Here we are forcing the Manager class to implement a WorkOnTask() method without a purpose. This is wrong. The design violates ISP. Let's correct the design.

Since we have three roles,

  1. Manager, that can only divide and assign the tasks,

  2. TeamLead that can divide and assign the tasks and can work on them as well,

  3. The programmer that can only work on tasks, we need to divide the responsibilities by segregating the ILead interface. An interface that provides a contract for WorkOnTask().

public interface IProgrammer  
{  
   void WorkOnTask();  
}

An interface that provides contracts to manage the tasks:

public interface ILead  
{  
   void AssignTask();  
   void CreateSubTask();  
}

Then the implementation becomes:

public class Programmer: IProgrammer  
{  
   public void WorkOnTask()  
   {  
      //code to implement to work on the Task.  
   }  
}  
public class Manager: ILead  
{  
   public void AssignTask()  
   {  
      //Code to assign a Task  
   }  
   public void CreateSubTask()  
   {  
   //Code to create a sub taks from a task.  
   }  
}  

TeamLead can manage tasks and can work on them if needed. Then the TeamLead class should implement both of the IProgrammer and ILead interfaces.

public class TeamLead: IProgrammer, ILead  
{  
   public void AssignTask()  
   {  
      //Code to assign a Task  
   }  
   public void CreateSubTask()  
   {  
      //Code to create a sub task from a task.  
   }  
   public void WorkOnTask()  
   {  
      //code to implement to work on the Task.  
   }  
}  

D: Dependency Inversion Principle (DIP)

One should depend upon abstractions, rather than concrete implementations.

The DIP states that "high-level modules/classes should not depend on low-level modules/classes. Both should depend upon abstractions. Secondly, abstractions should not depend upon details. Details should depend upon abstractions".

High-level modules/classes implement business rules or logic in a system (application). Low-level modules/classes deal with more detailed operations; in other words they may deal with writing information to databases or passing messages to the operating system or services.

A high-level module/class that has a dependency on low-level modules/classes or some other class and knows a lot about the other classes it interacts with is said to be tightly coupled. When a class knows explicitly about the design and implementation of another class, it raises the risk that changes to one class will break the other class. So we must keep these high-level and low-level modules/classes loosely coupled as much as we can. To do that, we need to make both of them dependent on abstractions instead of knowing each other.

DIP Example

Suppose we need to work on an error logging module that logs exception stack traces into a file. Simple, isn't it?

The following are the classes that provide the functionality to log a stack trace into a file.

public class FileLogger  
{  
   public void LogMessage(string stackTrace)  
   {  
      //code to log stack trace into a file.  
   }  
}  
public class ExceptionLogger  
{  
   public void LogIntoFile(Exception ex)  
   {  
      FileLogger fileLogger = new FileLogger();  
      fileLogger.LogMessage(GetUserReadableMessage(ex));  
   }  
   private GetUserReadableMessage(Exception ex)  
   {  
      string msg = string.Empty;  
      // code to convert Exception's stack trace and message 
      // to user readable format.  
      ....  
      ....  
      return msg;  
   }  
}  

A client class exports data from many files to a database.

public class DataExporter  
{   
   public void ExportDataFromFile()  
   {  
      try {  
         // code to export data from files to database.  
      }  
      catch(Exception ex)  
      {  
         new ExceptionLogger().LogIntoFile(ex);  
      }
   }     
}  

Looks good. We sent our application to the client. But our client wants to store this stack trace in a database if an IO exception occurs. Hmm... okay, no problem. We can implement that too. Here we need to add one more class that provides the functionality to log the stack trace into the database and an extra method in ExceptionLogger to interact with our new class to log the stack trace.

public class DbLogger  
{  
   public void LogMessage(string msg)  
   {  
      //Code to write message in database.  
   }  
}  
public class FileLogger  
{  
   public void LogMessage(string st)  
   {  
      //code to log stack trace into a file.  
   }  
}  
public class ExceptionLogger  
{  
   public void LogIntoFile(Exception ex)  
   {  
      FileLogger fileLogger = new FileLogger();  
      fileLogger.LogMessage(GetUserReadableMessage(ex));  
   }  
   public void LogIntoDataBase(Exception ex)  
   {  
      DbLogger dbLogger = new DbLogger();  
      dbLogger.LogMessage(GetUserReadableMessage(ex));  
   }  
   private string GetUserReadableMessage(Exception ex)  
   {  
      string msg = string.Empty;  
      // code to convert Exception's stack trace and message 
      // to user readable format.  
      ....  
      ....  
      return msg;  
   }  
}  

public class DataExporter  
{  
   public void ExportDataFromFile()  
   {  
      try {  
         //code to export data from files to database.  
      }  
      catch(IOException ex)  
      {  
         new ExceptionLogger().LogIntoDataBase(ex);  
      }  
      catch(Exception ex)  
      {  
         new ExceptionLogger().LogIntoFile(ex);  
      }  
   }  
}  

Looks fine for now. But whenever the client wants to introduce a new logger, we need to alter ExceptionLogger by adding a new method. If we continue doing this after some time then we will see a fat ExceptionLogger class with a large set of methods that provide the functionality to log a message into various targets. Why does this issue occur? Because ExceptionLogger directly contacts the low-level classes FileLogger and DbLogger to log the exception. We need to alter the design so that this ExceptionLogger class can be loosely coupled with those classes. To do that we need to introduce an abstraction between them so that ExceptionLogger can contact the abstraction to log the exception instead of depending on the low-level classes directly.

public interface ILogger  
{  
   void LogMessage(string aString);  
} 

Now our low-level classes need to implement this interface.

public class DbLogger: ILogger  
{  
   public void LogMessage(string aMessage)  
   {  
      //Code to write message in database.  
   }  
}  
public class FileLogger: ILogger  
{  
   public void LogMessage(string aStackTrace)  
   {  
      //code to log stack trace into a file.  
   }  
}  

Now, we move to the low-level class's initiation from the ExcetpionLogger class to the DataExporter class to make ExceptionLogger loosely coupled with the low-level classes FileLogger and EventLogger. And by doing that we are giving provision to DataExporter class to decide what kind of Logger should be called based on the exception that occurs.

public class ExceptionLogger  
{  
   private ILogger _logger;  
   public ExceptionLogger(ILogger aLogger)  
   {  
      this._logger = aLogger;  
   }  
   public void LogException(Exception aException)  
   {  
      string strMessage = GetUserReadableMessage(aException);  
      this._logger.LogMessage(strMessage);  
   }  
   private string GetUserReadableMessage(Exception aException)  
   {  
      string strMessage = string.Empty;  
      //code to convert Exception's stack trace and message to user readable format.  
      ....  
      ....  
      return strMessage;  
   }  
}  
public class DataExporter  
{  
   public void ExportDataFromFile()  
   {  
      ExceptionLogger _exceptionLogger;  
      try {  
         //code to export data from files to database.  
      }  
      catch(IOException ex)  
      {  
         _exceptionLogger = new ExceptionLogger(new DbLogger());  
         _exceptionLogger.LogException(ex);  
      }  
      catch(Exception ex)  
      {  
         _exceptionLogger = new ExceptionLogger(new FileLogger());  
         _exceptionLogger.LogException(ex);  
      }  
   }  
} 

We successfully removed the dependency on low-level classes. This ExceptionLogger doesn't depend on the FileLogger and EventLogger classes to log the stack trace. We don't need to change the ExceptionLogger's code anymore for any new logging functionality. We need to create a new logging class that implements the ILogger interface and must add another catch block to the DataExporter class's ExportDataFromFile method.

public class EventLogger: ILogger  
{  
   public void LogMessage(string aMessage)  
   {  
      //Code to write message in system's event viewer.  
   }  
}

And we need to add a condition in the DataExporter class as in the following:

public class DataExporter  
{  
   public void ExportDataFromFile()  
   {  
      ExceptionLogger _exceptionLogger;  
      try {  
         //code to export data from files to database.  
      }  
      catch(IOException ex)  
      {  
         _exceptionLogger = new ExceptionLogger(new DbLogger());  
         _exceptionLogger.LogException(ex);  
      }  
      catch(SqlException ex)  
      {  
         _exceptionLogger = new ExceptionLogger(new EventLogger());  
         _exceptionLogger.LogException(ex);  
      }  
      catch(Exception ex)  
      {  
         _exceptionLogger = new ExceptionLogger(new FileLogger());  
         _exceptionLogger.LogException(ex);  
      }  
   }  
}

Looks good. But we introduced the dependency here in the DataExporter class's catch blocks. Yeah, someone must take the responsibility to provide the necessary objects to the ExceptionLogger to get the work done. Let me explain it with a real-world example. Suppose we want to have a wooden chair with specific measurements and the kind of wood to be used to make that chair. Then we can't leave the decision making on measurements and the wood to the carpenter. Here his job is to make a chair based on our requirements with his tools and we provide the specifications to him to make a good chair. So what is the benefit we get by the design? Yes, we definitely have a benefit with it. We need to modify both the DataExporter class and ExceptionLogger class whenever we need to introduce a new logging functionality. But in the updated design we need to add only another catch block for the new exception logging feature. Coupling is not inherently evil. If you don't have some amount of coupling, your software will not do anything for you. The only thing we need to do is understand the system, requirements, and environment properly and find areas where DIP should be followed.

Last updated