SOLID With .Net Core

Introduction

 
This article will explain the SOLID principles, which one of those acronyms means alongside a practical example of an architectural problem that we could use in order to fix the problem.
 

What are the SOLID principles?

 
A SOLID principle is a group of 5 different design patterns whose main focus is to create loosely coupled architectures with a high level of maintainability. The name SOLID comes from the acronym of its five principles,
  • S - Single Responsability Principle;
  • O - Open-Closed Principle;
  • L - Liskov Substitution Principle;
  • I - Interface Segregation Principle;
  • D - Dependency Inversion Principle.
If in your project you have the common problem to solve a bug and create two different bugs then you must start to think about using the SOLID principles in order to have a cleaner and more organized code, which does not break other features when you are working in a specific feature.
 

S - SRP - Single Responsibility Principle 

 
“A class should have one, and only one, a reason to change.”  (Robert C. Martin)
 
Avoiding Jack of all Trades' classes, the Single Responsibility Principle says that your class should have a single responsibility. This means that you should avoid, at all costs, having classes with multiple functionalities.
 
Imagine doing maintenance in a class with multiples functionalities, the risk of fixing one functionality but breaking other functionalities as a side-effect is extremely high. To overcome those kinds of situations you should apply the Single Responsibility Principle.
 
One great example of the Single Responsibility Principle being applied is the 3-tier projects architectures, where each tier is responsible only for their tasks. Ie.: the business layer is responsible to validate business logics where the repository layer is responsible to manipulate the database.
 

O - OCP - Open/Closed Principle

 
“A class is closed, since it may be compiled, stored in a library, baselined, and used by client classes. But it is also open, since any new class may use it as parent, adding new features. When a descendant class is defined, there is no need to change the original or to disturb its clients.” (Bertrand Meyer)
 
The topic here is also to avoid Jack of All Trades' classes but in a different manner. The open-closed says that instead of modifying your base classes to add more features you should create a new class with those features, and this class will be inheriting the base class.
 
Imagine having a class that based on the input could go through one workflow or another workflow completely different, you will probably manage that with conditional statements.
 
Now, imagine when you need to do maintenance in one of those workflows. What is the risk of breaking, by mistake, the other ones?
 
The Open-Closed Principle says that you must have a base class that should not be modified to add new functionalities. Instead, you should have a new class inheriting the base class with those new functionalities. In this case, when you need to do maintenance in a specific workflow you are certain that will have no side effects in the others workflows.
 

L - LSP - Liskov Substitution Principle

 
“Subtypes must be substitutable for their base types.” (Barbara Liskov)
 
The main point from the Liskov Substitution Principle is to create a base class in order to be inherited from its subtypes. 
 
The Liskov Substitution Principle states that if we change our class for its base class we should not have different behaviour. Instead, if we change our subclasses by our base class without breaking the application because our base classes must behave in the same way as our subclasses. In this case, if we need to replace our subclasses for another subclass we would not need to refactor anything because it would be a simple substitution and everything would still be working the same.
 

I - ISP - Interface Segregation Principle

 
“No client should be forced to depend on methods it does not use.” (Robert C. Martin)
 
This principle is not the best friend of laziness, it is the worst friend of those projects when you place all your needed contracts in a single place, with this we are not going to be able to reuse those interfaces or, even worse, we will not be using every method in the contract. Instead of creating an interface with many contracts on it, you should create as many interfaces as possible by grouping common behaviours.
 
The Interface Segregation Principle says that we should segregate interfaces in order to do not depend on interfaces with a contract that will not be implemented. We should have smaller interfaces and depend on more than one interface if needed.
 

D - DIP - Dependency Inversion Principle

 
“High-level modules should not depend upon low-level modules. Both should depend upon abstractions” (Robert C. Martin)
 
Here we have the best friend of loosely coupled applications and unit testing. If you have ever needed to replace one dependency and to do this you had to refactor every method that this dependency was being called then you should use the Dependency Inversion Principle.
 
The Dependency Inversion Principle says that our classes should not depend on low-level modules because this created a strong coupled application, making it very difficult to unit test and substitute dependencies. Instead, our classes should receive in their constructor the abstraction of their low-level dependencies, with this we may change our classes that implement the contract without breaking or needing to refactor the whole application. Also, we could easily mock our dependencies in order to create unit tests.
 
 

SOLID principles Practical Usage One-by-One

 
SRP - The Problem - Class that sum two numbers and log it
 
Here we have a problem that we can use the Single Responsability Principle to fix it. A class with two functionalities, the first is to sum two numbers and the second is to log this operation
  1. class Problem    
  2. {    
  3.     public int Sum(int numberOne, int numberTwo)    
  4.     {    
  5.         int result = numberOne + numberTwo;    
  6.         LogCalculations("Sum Operation. Number one: " + numberOne + ", Number two: " + numberTwo + ". Result: " + result);    
  7.         return result;    
  8.     }    
  9.   
  10.     private void LogCalculations(string message)    
  11.     {    
  12.         string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\log.txt";    
  13.         using (StreamWriter sw = File.CreateText(path))    
  14.         {    
  15.             sw.WriteLine(message);    
  16.         }    
  17.     }    
  18. }   
Applying the Single Responsibility Principle we would have two different classes:
  1. class Solution    
  2. {    
  3.     public int Sum(int numberOne, int numberTwo)    
  4.     {    
  5.         int result = numberOne + numberTwo;    
  6.         Logging.Log("Sum Operation. Number one: " + numberOne + ", Number two: " + numberTwo + ". Result: " + result);    
  7.         return result;    
  8.     }    
  9. }    
  10. public static class Logging    
  11. {    
  12.     public static void Log(string message)    
  13.     {    
  14.         string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\log.txt";    
  15.         using (StreamWriter sw = File.CreateText(path))    
  16.         {    
  17.             sw.WriteLine(message);    
  18.         }    
  19.     }    
  20. }  

OCP - The Problem 1 - Class to do math calculations

 
In this class, we receive as input one enumeration with the operation type and return the result from this operation. If we need to add or modify one operation, we would need to modify the class.
  1. public class MathCalculate    
  2. {    
  3.     public double Calculate(double numberA, double numberB, CalculationType calculationType)    
  4.     {    
  5.         double result = 0;    
  6.         switch (calculationType)    
  7.         {    
  8.             case CalculationType.addition:    
  9.                 result = numberA + numberB;    
  10.                 break;    
  11.             case CalculationType.multiplication:    
  12.                 result = numberA * numberB;    
  13.                 break;    
  14.             case CalculationType.subtraction:    
  15.                 result = numberA - numberB;    
  16.                 break;    
  17.             default:    
  18.                 break;    
  19.         }    
  20.         return result;    
  21.     }    
  22. }    
  23.   
  24. public enum CalculationType    
  25. {    
  26.     addition,    
  27.     multiplication,    
  28.     subtraction    
  29. } 
Applying the Open-Closed Principle we would have a base class "Calculation" and each operation would be a new class, inheriting from this base class. If we need to add or modify a new operation, then we would need to work only in the class of this operation
  1. public abstract class BaseCalculation    
  2. {    
  3.     public abstract double Calculate(double numberA, double numberB);    
  4. }    
  5.   
  6. public class AdditionCalculation : BaseCalculation    
  7. {    
  8.     public override double Calculate(double numberA, double numberB)    
  9.     {    
  10.         return numberA + numberB;    
  11.     }    
  12. }    
  13. public class MultiplicationCalculation : BaseCalculation    
  14. {    
  15.     public override double Calculate(double numberA, double numberB)    
  16.     {    
  17.         return numberA * numberB;    
  18.     }    
  19. }    
  20.   
  21. public class SubtractionCalculation : BaseCalculation    
  22. {    
  23.     public override double Calculate(double numberA, double numberB)    
  24.     {    
  25.         return numberA - numberB;    
  26.     }    
  27. }    
  28.   
  29. public class DivisionCalculation : BaseCalculation    
  30. {    
  31.     public override double Calculate(double numberA, double numberB)    
  32.     {    
  33.         return numberA / numberB;    
  34.     }    
  35. } 

OCP - The Problem 2 - Email sender with validations

 
If we need to add or modify the validations, we would need to modify the email sender class, risking to break the email sender functionality.
  1. public class MailSender    
  2. {    
  3.     public void SendMail(string subject, string body, string recipient)    
  4.     {    
  5.         SmtpClient smtpClient = new SmtpClient("smtp.gmail.com")    
  6.         {    
  7.             Port = 587,    
  8.             Credentials = new NetworkCredential("email""password"),    
  9.             EnableSsl = true,    
  10.         };    
  11.   
  12.         //validate recipient's domain    
  13.         if (!recipient.ToString().EndsWith("@thiago.com"))    
  14.         {    
  15.             Console.WriteLine("Mail destinatary not in the domain");    
  16.             return;    
  17.         }    
  18.   
  19.         //validate body    
  20.         if (string.IsNullOrEmpty(body))    
  21.         {    
  22.             Console.WriteLine("Mail body is empty.");    
  23.             return;    
  24.         }    
  25.   
  26.         smtpClient.SendAsync("thiago@thiago.com", recipient, subject, body, null);    
  27.     }    
  28. } 
Applying the open-closed principle to solve this problem we would have this email sender class receiving a list of validations. When we need to add or modify one of those validations would not be necessary to update the mail sender class:
  1. public class MailClass    
  2. {    
  3.     public string Subject { getset; }    
  4.     public string Body { getset; }    
  5.     public string Recipient { getset; }    
  6. }    
  7.   
  8. public interface IValidation<T>    
  9. {    
  10.     bool Validate(T mail);    
  11. }    
  12.   
  13.   
  14. public class DomainValidation : IValidation<MailClass>    
  15. {    
  16.     public bool Validate(MailClass mail)    
  17.     {    
  18.         if (mail.Recipient.ToString().EndsWith("@thiago.com"))    
  19.             return false;    
  20.   
  21.         return true;    
  22.     }    
  23. }    
  24. public class BodyValidation : IValidation<MailClass>    
  25. {    
  26.     public bool Validate(MailClass mail)    
  27.     {    
  28.         if (string.IsNullOrEmpty(mail.Body))    
  29.             return false;    
  30.   
  31.         return true;    
  32.     }    
  33. }    
  34.   
  35. public class Main    
  36. {    
  37.     public void SendMail(MailClass mailClass, List<IValidation<MailClass>> validations)    
  38.     {    
  39.         List<bool> validationsResult = new List<bool>();    
  40.         validations.ForEach(x => validationsResult.Add(x.Validate(mailClass)));    
  41.   
  42.         if (!validationsResult.Any(x => !x))    
  43.         {    
  44.             SmtpClient smtpClient = new SmtpClient("smtp.gmail.com")    
  45.             {    
  46.                 Port = 587,    
  47.                 Credentials = new NetworkCredential("email""password"),    
  48.                 EnableSsl = true,    
  49.             };    
  50.   
  51.             smtpClient.SendAsync("thiago@thiago.com", mailClass.Recipient, mailClass.Subject, mailClass.Body, null);    
  52.         };    
  53.     }    
  54. } 

OCP - Extension Methods

 
We can also make usage of extension methods in order to extend objects without modifying their base behaviour. The following code extends the String object, adding this new method on it:
  1. public static class SolutionThree    
  2. {    
  3.     public static string ThiagoString(this string normalString)    
  4.     {    
  5.         return "Thiago's String is: " + normalString;    
  6.     }    
  7. }   
 

LSP - The Problem - Having a subtraction class inheriting from an addition class

 
In this example, we have an addition class working fine and then we extended it, wrongly, creating the subtraction class. If we replace the subtraction class with the base class (addition) our output will differ.
  1. public class AdditionCalculation    
  2. {    
  3.     public AdditionCalculation(int numberA, int numberB)    
  4.     {    
  5.         this.NumberB = numberB;    
  6.         this.NumberA = numberA;    
  7.     }    
  8.     public int NumberA { getset; }    
  9.     public int NumberB { getset; }    
  10.     public virtual int Calculate()    
  11.     {    
  12.         return this.NumberA + NumberB;    
  13.     }    
  14. }    
  15. public class SubtractionCalculation : AdditionCalculation    
  16. {    
  17.     public SubtractionCalculation(int numberA, int numberB) : base(numberA, numberB)    
  18.     {    
  19.     }    
  20.   
  21.     public new int Calculate()    
  22.     {    
  23.         return NumberA - NumberB;    
  24.     }    
  25. } 
 
 
Applying the Liskov Substitution Principle to solve this problem we have a base class then we have the addition and subtraction classes inheriting from this base class. If we change our class with the base class our output is not going to be affected. 
  1. public abstract class MathCalculate    
  2. {    
  3.     public MathCalculate(int numberA, int numberB)    
  4.     {    
  5.         this.NumberB = numberB;    
  6.         this.NumberA = numberA;    
  7.     }    
  8.     public int NumberA { getset; }    
  9.     public int NumberB { getset; }    
  10.   
  11.     public abstract int Calculate();    
  12. }    
  13. public class Addition : MathCalculate    
  14. {    
  15.     public Addition(int numberA, int numberB) : base(numberA, numberB)    
  16.     {    
  17.     }    
  18.   
  19.     public override int Calculate()    
  20.     {    
  21.         return this.NumberA + NumberB;    
  22.     }    
  23. }    
  24. public class Subtraction : MathCalculate    
  25. {    
  26.     public Subtraction(int numberA, int numberB) : base(numberA, numberB)    
  27.     {    
  28.     }    
  29.   
  30.     public override int Calculate()    
  31.     {    
  32.         return NumberA - NumberB;    
  33.     }    
  34. }   
 

ISP - The Problem - A single interface for many type of classes

 
In this example, we have a single interface called IAnimal that is used for both Human and Whale classes. The problem is that not the whole contract fit both items because, as we all know, whales do not walk.
  1. public interface IAnimal    
  2. {    
  3.     void Walk();    
  4.     void Breath();    
  5.     void Eat();    
  6.     void Argument();    
  7. }    
  8.   
  9. public class Human : IAnimal    
  10. {    
  11.     public void Argument()    
  12.     {    
  13.         // Argumentation    
  14.     }    
  15.   
  16.     public void Breath()    
  17.     {    
  18.         // Breathing    
  19.     }    
  20.   
  21.     public void Eat()    
  22.     {    
  23.         // Eating    
  24.     }    
  25.   
  26.     public void Walk()    
  27.     {    
  28.         // Walk    
  29.     }    
  30. }    
  31. public class Whale : IAnimal    
  32. {    
  33.     public void Argument()    
  34.     {    
  35.         // Argumentation    
  36.     }    
  37.   
  38.     public void Breath()    
  39.     {    
  40.         // Breathing    
  41.     }    
  42.   
  43.     public void Eat()    
  44.     {    
  45.         // Eating    
  46.     }    
  47.   
  48.     public void Walk()    
  49.     {    
  50.         throw new NotImplementedException();    
  51.     }    
  52. } 
Applying the Interface Segregation Principle we break the single interface in smaller interfaces with common methods and then we only use the interfaces that we need in our classes.
  1. public interface IFeed {    
  2.     void Eat();    
  3. }    
  4.   
  5. public interface IArgument    
  6. {    
  7.     void Argument();    
  8. }    
  9.   
  10. public interface IGroundMoviment    
  11. {    
  12.     void Walk();    
  13. }    
  14. public interface IAirMoviment    
  15. {    
  16.     void Fly();    
  17. }    
  18. public interface IWaterMoviment    
  19. {    
  20.     void Swimm();    
  21. }    
  22.   
  23. public class Human : IGroundMoviment, IArgument, IFeed    
  24. {    
  25.     public void Argument()    
  26.     {    
  27.         // Argument    
  28.     }    
  29.   
  30.     public void Eat()    
  31.     {    
  32.         // Eat    
  33.     }    
  34.   
  35.     public void Walk()    
  36.     {    
  37.         // Walk    
  38.     }    
  39. }    
  40. public class Whale : IWaterMoviment, IFeed    
  41. {    
  42.     public void Eat()    
  43.     {    
  44.         // Eat    
  45.     }    
  46.   
  47.     public void Swimm()    
  48.     {    
  49.         // Swimm    
  50.     }    
  51. } 

DIP - The Problem - Strong Coupled Application

 
In this example, we need to instantiate our dependency inside our method, creating a strong coupled application. If we want to replace this dependency we would need a lot of work, needing to change those dependencies at every method that is being used. Also, it is much more difficult to unit test this layer because it is much harder to mock this dependency. 
  1. public class BusinessLayer    
  2. {    
  3.     public void AddItem(int itemId)    
  4.     {    
  5.         RepositoryLayer repositoryLayer = new RepositoryLayer();    
  6.         if (!string.IsNullOrEmpty(repositoryLayer.GetItem(itemId)))    
  7.             repositoryLayer.Update();    
  8.         else    
  9.             repositoryLayer.Create();    
  10.     }    
  11. }    
  12. public class RepositoryLayer    
  13. {    
  14.     public void Create()    
  15.     {    
  16.         //save data into the Database    
  17.     }    
  18.     public void Delete()    
  19.     {    
  20.         //delete data from the Database    
  21.     }    
  22.     public void Update()    
  23.     {    
  24.         //update data in the Database    
  25.     }    
  26.     public string GetItem(int itemId)    
  27.     {    
  28.         //get item from the Database    
  29.         return "item";    
  30.     }    
  31. } 
Applying the Dependency Inversion Principle, we receive the interface of our dependency in the class constructor. If we need to change the class that implements this dependency contract it would not be necessary to refactor any method where we use this dependency.
  1. public class BusinessLayer    
  2. {    
  3.     private readonly IRepositoryLayer repositoryLayer;    
  4.   
  5.     public BusinessLayer(IRepositoryLayer repositoryLayer)    
  6.     {    
  7.         this.repositoryLayer = repositoryLayer;    
  8.     }    
  9.     public void AddItem(int itemId)    
  10.     {    
  11.         if (!string.IsNullOrEmpty(repositoryLayer.GetItem(itemId)))    
  12.             repositoryLayer.Update();    
  13.         else    
  14.             repositoryLayer.Create();    
  15.     }    
  16. }    
  17. public interface IRepositoryLayer    
  18. {    
  19.     void Create();    
  20.   
  21.     void Delete();    
  22.   
  23.     void Update();    
  24.   
  25.     string GetItem(int itemId);    
  26. }
Congratulations! You have successfully applied the SOLID principles using .Net Core.