SOLID Design Principles

Introduction

 
SOLID Design Principles is an acronym for Five Design Principles.
  • Single Responsibility Principle.(SRP)
  • Interface Segregation Principle.(ISP)
  • Open Closed Principle.(OCP)
  • Liskov Substitution Principle.(LSP)
  • Dependency Inversion Principle.(DIP)

Single Responsibility Principle

 
According to the SRP every class or module has responsibility over a single part of the functionality provided by the software. It should have only one reason to change and that is if the single piece of responsibility needs a change.
  1. public interface IUser  
  2. {  
  3.    void AddUser();  
  4.    void RemoveUser();  
  5.    void UpdateUser();  
  6.    void Logger();  
  7.    void Message();  
  8. }  
If we have a deep look into the above methods we could clearly discover that for IUser it does not make sense for methods like Log() and Message() to be a part of it. So, we will be breaking it down into separate interfaces.
  1. public interface IUser  
  2. {  
  3.    void AddUser();  
  4.    void RemoveUser();  
  5.    void UpdateUser();  
  6. }  
  7. public interface ILog  
  8. {  
  9.    void Logger();  
  10. }  
  11. public interface IMessage  
  12. {  
  13.    void Message();  
  14. }  
From here we could say all three interfaces are performing their own individual responsibilities. Now we will Use Dependency injection to implement the following code.
  1. public class User : IUser  
  2. {  
  3.    public void AddUser()  
  4.    {  
  5.       Console.WriteLine("Added User");  
  6.    }  
  7.    public void RemoveUser()  
  8.    {  
  9.       Console.WriteLine("Removed User");  
  10.    }  
  11.    public void UpdateUser()  
  12.    {  
  13.       Console.WriteLine("User Updated");  
  14.    }  
  15. }  
  16.    
  17. public class Log : ILog  
  18. {  
  19.    public void Logger()  
  20.    {  
  21.       Console.WriteLine("Logged Error");  
  22.    }  
  23. }  
  24.    
  25. public class Msg : IMessage  
  26. {  
  27.    public void Message()  
  28.    {  
  29.       Console.WriteLine("Messaged Sent");  
  30.    }  
  31. }  
  32. class Class_DI  
  33. {  
  34.    private readonly IUser _user;  
  35.    private readonly ILog _log;  
  36.    private readonly IMessage _msg;  
  37.    public Class_DI(IUser user, ILog log, IMessage msg)  
  38.    {  
  39.       this._user = user;  
  40.       this._log = log;  
  41.       this._msg = msg;  
  42.    }  
  43.    public void User()  
  44.    {  
  45.       this._user.AddUser();  
  46.       this._user.RemoveUser();  
  47.       this._user.UpdateUser();  
  48.    }  
  49.    public void Log()  
  50.    {  
  51.       this._log.Logger();  
  52.    }  
  53.    public void Msg()  
  54.    {  
  55.       this._msg.Message();  
  56.    }  
  57. }  
  58.    
  59. class Example1  
  60. {  
  61.    public static void Main()  
  62.    {  
  63.       Class_DI di = new Class_DI(new User(), new Log(), new Msg());  
  64.       di.User();  
  65.       di.Log();  
  66.       di.Msg();  
  67.       Console.ReadLine();  
  68.    }  
  69. }  
  70.    
  71. ************End of Single Responsibility Principle*********  

Interface Segregation Principle

 
ISP states that no client should be forced to depend on methods it does not use. Rather than having one fat interface it should split into many smaller and relevant interfaces so that clients will only have to know about the methods that are relevant to them .
 
Note
We already covered ISP with the previous example of SRP . 
  1. public interface IUser {  
  2.     void AddUser();  
  3.     void RemoveUser();  
  4.     void UpdateUser();  
  5.     void Logger();  
  6.     void Message();  
  7. }  
Big fat interfaces split into relevant interfaces for the client.
  1. public interface IUser {  
  2.     void AddUser();  
  3.     void RemoveUser();  
  4.     void UpdateUser();  
  5. }  
  6. public interface ILog {  
  7.     void Logger();  
  8. }  
  9. public interface IMessage {  
  10.     void Message();  
  11. } ** ** ** ** ** ** End of Interface Segregation Principle ** ** ** ** *  

Open Closed Principle

 
OCP states Software Entities should be open for extension but closed for modification.
 
Here we are calculating the bonus of a teacher by taking a simple Console Applicaton 
  1. public class Teacher  
  2. {  
  3.    public int EmpId;  
  4.    public string Name;  
  5.    public Teacher(int id, string name)  
  6.    {  
  7.       this.EmpId = id;  
  8.       this.Name = name;  
  9.    }  
  10.    public decimal Bonus(decimal salary)  
  11.    {  
  12.       return salary * .2M;  
  13.    }  
  14. }  
  15. class Example2  
  16. {  
  17.    public static void Main()  
  18.    {  
  19.       Teacher teacher = new Teacher(101, "Zeko");  
  20.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher.EmpId,teacher.Name,teacher.Bonus(10000));  
  21.       Console.ReadLine();  
  22.    }  
  23. }   
Teacher Employee ID: 101 Name: Zeko Bonus: 2000.0
 
Let's now assume that there is an enhancement of calculating the bonuses of Permanent and Temporary Teacher. To implement that we need to modify the existing class and its method . From here we could clearly say that it is violating the Open Closed Principle.
 
Violating the Rule
  1. public class Teacher  
  2. {  
  3.    public int EmpId;  
  4.    public string Name;  
  5.    public string EmpType;  
  6.    public Teacher(int id, string name, string emptype)  
  7.    {  
  8.       this.EmpId = id;  
  9.       this.Name = name;  
  10.       this.EmpType = emptype;  
  11.    }  
  12.    public decimal Bonus(decimal salary)  
  13.    {  
  14.       if(EmpType=="Permanent")  
  15.          return salary * .2M;  
  16.       else  
  17.          return salary * .1M;  
  18.    }  
  19. }  
Permanent Teacher Employee ID: 101 Name: Zeko Bonus: 2000.0
 
Temporarty Teacher Employee ID: 102 Name: Priyanka Bonus: 1000.0
 
So what should we do?
 
To abide by the guidelines of OCP we would make the Teacher class as an abstract class having Bonus() as an abstract method. 
  1. public abstract class Teacher  
  2. {  
  3.    public int EmpId;  
  4.    public string Name;  
  5.    public Teacher(int id, string name)  
  6.    {  
  7.       this.EmpId = id;  
  8.       this.Name = name;  
  9.    }  
  10.    public abstract decimal Bonus(decimal salary);  
  11. }  
Now the school could easily calculate the bonus of their Permanent Teachers by implementing the below class
  1. public class PermanentTeacher : Teacher  
  2. {  
  3.    public PermanentTeacher(int id, string name):base(id,name)  
  4.    {  
  5.    }  
  6.    public override decimal Bonus(decimal salary)  
  7.    {  
  8.       return salary * .2M;  
  9.    }  
  10. }  
  11.     
  12. class Example2  
  13. {  
  14. public static void Main()  
  15. {  
  16.    Teacher teacher = new PermanentTeacher(101, "Zeko");  
  17.    Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher.EmpId,teacher.Name,teacher.Bonus(10000));  
  18.    Console.ReadLine();  
  19. }  
  20. }  
The advantage of using abstract class here is if the school in the future decides to give bonuses for their Temporary Teachers as well then we do not have to modify the Teacher class again as we did before, as it is open for extention now. 
 
Add one more TemporaryTeacher class just like the Permanent Teacher .
 
Final Implementation 
  1. public abstract class Teacher  
  2. {  
  3.    public int EmpId;  
  4.    public string Name;  
  5.    public Teacher(int id, string name)  
  6.    {  
  7.       this.EmpId = id;  
  8.       this.Name = name;  
  9.    }  
  10.    public abstract decimal Bonus(decimal salary);  
  11. }  
  12.    
  13. public class PermanentTeacher : Teacher  
  14. {  
  15.    public PermanentTeacher(int id, string name):base(id,name)  
  16.    {  
  17.    }  
  18.    public override decimal Bonus(decimal salary)  
  19.    {  
  20.       return salary * .2M;  
  21.    }  
  22. }  
  23.     
  24. public class TemporaryTeacher : Teacher  
  25. {  
  26.    public TemporaryTeacher(int id, string name) : base(id, name)  
  27.    {  
  28.    }  
  29.    public override decimal Bonus(decimal salary)  
  30.    {  
  31.       return salary * .1M;  
  32.    }  
  33. }  
  34.     
  35. class Example2  
  36. {  
  37.    public static void Main()  
  38.    {  
  39.       Teacher teacher = new PermanentTeacher(101, "Zeko");  
  40.       Teacher teacher2 = new TemporaryTeacher(102, "Priyanka");  
  41.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher.EmpId,teacher.Name,teacher.Bonus(10000));  
  42.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher2.EmpId, teacher2.Name, teacher2.Bonus(10000));   
  43.       Console.ReadLine();  
  44.    }  
  45. }  
  46.    
  47. Employee ID: 101 Name: Zeko       Bonus: 2000.0  
  48. Employee ID: 102 Name: Priyanka Bonus: 1000.0  
  49.    
  50. Hence the Teacher  class is now open for extention but closed for modification which does not vioalte the OCP.  
  51.    
  52.    
  53. ************End of Open Closed Principle*********   

Liskov Substitution Principle

 
LSP states that Derived types can be completely substitutable for their base types. The point to note here is no new exception should be thrown by the subtype.
 
In our previous example of Open Closed Principle we have followed one rule of LSP where we are actually substituing the base class Teacher with the derived class PermanentTeacher and TemporaryTeacher 
  1. class Example2  
  2. {  
  3.    public static void Main()  
  4.    {  
  5.       Teacher teacher = new PermanentTeacher(101, "Zeko");  
  6.       Teacher teacher2 = new TemporaryTeacher(102, "Priyanka");  
  7.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher.EmpId,teacher.Name,teacher.Bonus(10000));  
  8.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher2.EmpId, teacher2.Name, teacher2.Bonus(10000));  
  9.    Console.ReadLine();  
  10.    }  
  11. }  
So , again let's assume that the school has made another call of hiring a Contract Teacher who will not get any bonus since the person is hired on contract.
 
To implement this let's add the another class similar to Permanent and Temporary Class.
  1. public class ContractTeacher : Teacher  
  2. {  
  3.    public ContractTeacher(int id, string name) : base(id, name)  
  4.    {  
  5.    }  
  6.    public override decimal Bonus(decimal salary)  
  7.    {  
  8.       throw new NotImplementedException();  
  9.    }  
  10. }  
  11.    
  12.    
  13. class Example2  
  14. {  
  15.    public static void Main()  
  16.    {  
  17.       Teacher teacher = new PermanentTeacher(101, "Zeko");  
  18.       Teacher teacher2 = new TemporaryTeacher(102, "Priyanka");  
  19.       Teacher teacher3 = new ContractTeacher(103, "Partha");   
  20.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher.EmpId,teacher.Name,teacher.Bonus(10000));  
  21.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher2.EmpId, teacher2.Name, teacher2.Bonus(10000));  
  22.       Console.WriteLine("Employee ID: {0} Name: {1} Bonus: {2}", teacher3.EmpId, teacher3.Name, teacher3.Bonus(50000));   
  23.       Console.ReadLine();  
  24.    }  
  25. }  
If you run the solution now we can see it violates the LSP since the subtype here is throwing an exception.
 

Solution

 
We will go ahead and modify the structure and add two separate interfaces. Refer to the below code.
 
Final Implementation
  1. interface IBonus  
  2. {  
  3.    decimal Bonus(decimal salary);  
  4. }  
  5. interface ITeacher  
  6. {  
  7.    int EmpId { getset; }  
  8.    string Name { getset; }  
  9.    decimal GetSalary();  
  10. }  
  11. public abstract class Teacher : ITeacher,IBonus  
  12. {  
  13.    public int EmpId { get ; set; }  
  14.    public string Name { get ; set ; }  
  15.    public Teacher(int id, string name)  
  16.    {  
  17.       this.EmpId = id;  
  18.       this.Name = name;  
  19.    }  
  20.    public abstract decimal GetSalary();  
  21.    public abstract decimal Bonus(decimal salary);  
  22. }  
  23.    
  24.    
  25. public class PermanentTeacher : Teacher  
  26. {  
  27.    public PermanentTeacher(int id, string name) : base(id, name)  
  28.    {  
  29.    }  
  30.    public override decimal GetSalary()  
  31.    {  
  32.       return 10000;  
  33.    }  
  34.    public override decimal Bonus(decimal salary)  
  35.    {  
  36.       return salary * .2M;  
  37.    }  
  38. }  
  39. public class TemporaryTeacher : Teacher  
  40. {  
  41.    public TemporaryTeacher(int id, string name) : base(id, name)  
  42.    {  
  43.    }  
  44.    public override decimal GetSalary()  
  45.    {  
  46.       return 10000;  
  47.    }  
  48.    public override decimal Bonus(decimal salary)  
  49.    {  
  50.       return salary * .1M;  
  51.    }  
  52. }  
  53.    
  54.    
  55. //This class will have no Bonus  
  56. public class ContractTeacher : ITeacher  
  57. {  
  58.    public int EmpId { get ; set ; }  
  59.    public string Name { get ; set; }  
  60.    public ContractTeacher(int id, string name)  
  61.    {  
  62.       this.EmpId = id;  
  63.       this.Name = name;  
  64.    }  
  65.    public decimal GetSalary()  
  66.    {  
  67.       return 5000;  
  68.    }  
  69. }  
  70.    
  71.    
  72. class Example2  
  73. {  
  74.    public static void Main()  
  75.    {  
  76.       //Getting the Bonus detail with Salary  
  77.       Teacher teacher = new PermanentTeacher(101, "Zeko");  
  78.       Teacher teacher2 = new TemporaryTeacher(102, "Priyanka");  
  79.       Console.WriteLine("Employee ID: {0} Name: {1} Salary: {2} Bonus:{3}",       teacher.EmpId,teacher.Name,teacher.GetSalary(),teacher.Bonus(teacher.GetSalary()));  
  80.       Console.WriteLine("Employee ID: {0} Name: {1} Salary: {2} Bonus:{3}", teacher2.EmpId, teacher2.Name, teacher2.GetSalary(),       teacher2.Bonus(teacher2.GetSalary()));  
  81.       //Getting details without Bonus  
  82.       List<ITeacher> teachers = new List<ITeacher>();  
  83.       teachers.Add(new PermanentTeacher(101, "Zeko"));  
  84.       teachers.Add(new TemporaryTeacher(102, "Priyanka"));  
  85.       teachers.Add(new ContractTeacher(103, "Partha"));  
  86.       foreach (var obj in teachers)  
  87.       {  
  88.          Console.WriteLine("Employee ID: {0} Name: {1} Salary: {2} ", obj.EmpId, obj.Name, obj.GetSalary());  
  89.       }  
  90.       Console.ReadLine();  
  91.    }  
  92. }  
  93.    
  94. ************End of Liskov Substitution Principle*********  

Dependency Inversion Principle

 
As per DIP, high level modules should not depend on low level modules; rather both should depend on abstracions. Additionally abstraction should not depend on details. Details should depend on abstractions.
  1. public class Message  
  2. {  
  3.    public void SendMessage()  
  4.    {  
  5.       Console.WriteLine("Message Sent");  
  6.    }  
  7. }  
  8. public class Notification  
  9. {  
  10.    private Message _msg;  
  11.    public Notification()  
  12.    {  
  13.    _msg = new Message();  
  14.    }  
  15.    public void PromotionalNotification()  
  16.    {  
  17.       _msg.SendMessage();  
  18.    }  
  19. }  
  20. class Test_Notify  
  21. {  
  22.    public static void Main()  
  23.    {  
  24.    Notification notify = new Notification();  
  25.    notify.PromotionalNotification();  
  26.    Console.WriteLine();  
  27.    Console.ReadLine();  
  28.    }  
  29. }  
Note
The above Notification  class totally depends on Message class, because it only can send one type of notification. If we want to introduce two types of messages (Email,SMS) then we need to change the notification class also, hence it is called tightly coupled.
 
Now the best way to acheive the requirment is by implemention of Dependency Injection so that we can make it loosely coupled. 
 
If the topic of DI is completely new please refer to  this url for better understanding along with its  types.
 
Final Implemnetation
  1. public interface IMessage  
  2. {  
  3.    void SendMessage();  
  4. }  
  5. public class Email : IMessage  
  6. {  
  7.    public void SendMessage()  
  8.    {  
  9.    Console.WriteLine("Send Email");  
  10.    }  
  11. }  
  12. public class SMS : IMessage  
  13. {  
  14.    public void SendMessage()  
  15.    {  
  16.    Console.WriteLine("Send Sms");  
  17.    }  
  18. }  
  19. public class Notification  
  20. {  
  21.    private IMessage _msg;  
  22.    public Notification(IMessage msg)  
  23.    {  
  24.    this._msg = msg;  
  25.    }  
  26.    public void Notify()  
  27.    {  
  28.    _msg.SendMessage();  
  29.    }  
  30. }  
  31. class Test_Notify  
  32. {  
  33.    public static void Main()  
  34.    {  
  35.       Email email = new Email();  
  36.       //passing dependency  
  37.       Notification notify = new Notification(email);  
  38.       notify.Notify();  
  39.       SMS sms = new SMS();  
  40.       //passing depeNotification(email)ndency  
  41.       notify = new Notification(sms);  
  42.       notify.Notify();  
  43.       Console.WriteLine();  
  44.       Console.ReadLine();  
  45.    }  
  46. }  
Happy Learning...