Single Responsibility Principle in C-Sharp: Simplified

Let us start with understanding what is SRP?

Single Responsibility Principle says every class should have single responsibility and all the responsibility should be encapsulated in the class. To explain it further assume you are creating a creating class to Calculate Salary.

Now if you have two methods in class like below. Usually we can think of these two methods in a Salary class.

  1. CalculateSalaray
  2. PrintSalary

So you can say there are two responsibilities to class. With two responsibilities Salary class can be defined as below,

 class Salary

{
 public double wageperday { get; set; }
 public int attendence { get; set; }
 public double CalculateSalaray()
 {
 return this.wageperday * this.attendence;

}

public void PrintSalaray()
 {
 Console.WriteLine(this.wageperday * this.attendence);

}

}


As of Martin SRP means, “Class should have a single reason to change”. Reason to change can be seen as a Responsibility. On seeing closely you will find above class has two reasons to change,

  1. When formula for calculate salary is changing
  2. When print logic is changing

Since Salary class has two responsibility so there are two reasons to change it. We can say Salary class is not following Single Repository Principle.

We can summarize that

image

Next we need to find that how could we divide two responsibility in two separate class. So above Salary class can be divided into two separate classes. One class to CalculateSalary and another to PrintSalary.

Below is the class CalculateSalary. This class got only one responsibility to calculate salary.

class CalculateSalary
 {
 public double wageperday { get; set; }
 public int attendence { get; set; }
 public double CalculateSalaray()
 {
 return this.wageperday * this.attendence;

}
 }

 

Another class is PrintSalary. This class also got only one responsibility to print salary.

 class PrintSalary
 {

public void PrintSalaray(double salary)
 {
 Console.WriteLine(salary);

}
 }

Let us understand what we done now is divided Salary class in two separate classes. Salary class had two responsibilities and two reasons to change. Now we have created two classes respectively for CalculateSalary and PrintSalary.

image

Now at client these two classes can be used as below,

static void Main(string[] args)
 {
 CalculateSalary clcObject = new CalculateSalary();
 clcObject.wageperday = 300;
 clcObject.attendence = 20;
 var salary = clcObject.CalculateSalaray();
 PrintSalary prntObject = new PrintSalary();
 prntObject.PrintSalaray(salary);
 Console.ReadKey(true);

}

As of now you should have idea about Single Responsibility Principle. To summarize Single Responsibility Principle says a class should have single responsibility and only one reason to change. I hope you find this post useful. Thanks for reading.