Thursday, January 26, 2023

Added More Example of SOLID Principle

Let’s take a scenario of Garage service station functionality. It has 3 main functions; open gate, close gate and performing service. Below example violates SRP principle. The code below, violates SRP principle as it mixes open gate and close gate responsibilities with the main function of servicing of vehicle.


public class GarageStation

{

 public void DoOpenGate()

 {

 //Open the gate functinality

 }

 

 public void PerformService(Vehicle vehicle)

 {

 //Check if garage is opened

 //finish the vehicle service

 }

 

 public void DoCloseGate()

 {

 //Close the gate functinality

 }

}


We can correctly apply SRP by refactoring of above code by introducing interface. A new interface called IGarageUtility is created and gate related methods are moved to different class called GarageStationUtility.


public class GarageStation
{
 IGarageUtility _garageUtil;
 
 public GarageStation(IGarageUtility garageUtil)
 {
 this._garageUtil = garageUtil;
 }
 public void OpenForService()
 {
 _garageUtil.OpenGate();
 }
 public void DoService()
 {
 //Check if service station is opened and then
 //finish the vehicle service
 }
 public void CloseGarage()
 {
 _garageUtil.CloseGate();
 }
}
 public class GarageStationUtility : IGarageUtility
{
 public void OpenGate()
 {
 //Open the Garage for service
 }
 
 public void CloseGate()
 {
 //Close the Garage functionlity
 }
}
 
public interface IGarageUtility
{
 void OpenGate();
 void CloseGate(); 

} 



Open Close Principle:


public class Logger
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    public void Info(string message)
    {
        Console.WriteLine($"Info: {message}");
    }

    public void Debug(string message)
    {
        Console.WriteLine($"Debug: {message}");
    }
}

Now, some developers want to change debug messages to suit their needs. For example, they want to start debugging messages with "Dev Debug ->". So, to satisfy their need, you need to edit the code of the Logger class and either create a new method for them or modify the existing Debug() method. If you change the existing Debug() method then the other developers who don't want this change will also be affected.

One way to use OCP and solve this problem is to use class based-inheritance (polymorphism) and override methods.




No comments:

Post a Comment