Let us start with understanding what SRP? is
The Single Responsibility Pattern says every class should have a single responsibility and all the responsibility should be encapsulated in the class. To explain it further, assume you are creating a class to calculate salary.
There are two methods in the class as in the following. Usually we can think of these two methods in a Salary class.
- CalculateSalaray
- PrintSalary
So you can say there are two responsibilities of the class. The two responsibilities of the 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, "A class should have a single reason to change". The reason to change can be seen as a Responsibility. On seeing closely you will find the class above has the following two reasons to change:
- When formula for calculate salary is changing
- When print logic is changing
Since the Salary class has two responsibility, there are two reasons to change it. We can say the Salary class is not following the Single Repository Pattern.
We can summarize that as:
Next we need to find how to divide two responsibilities in two separate classes. So the above Salary class can be divided into two separate classes. One class, CalculateSalary and the other PrintSalary.
The following is the class CalculateSalary. This class has 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 has only one responsibility; to print salary.
class PrintSalary
{
public void PrintSalaray(double salary)
{
Console.WriteLine(salary);
}
}
Let us understand what we have done. We have the divided Salary class into two separate classes. The Salary class had two responsibilities and two reasons to change. Now we have created two classes respectively for CalculateSalary and PrintSalary.
Now at the 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);
}
You should now have an idea of the Single Responsibility Pattern. To summarize, the Single Responsibility Pattern says a class should have a single responsibility and only one reason to change. I hope you find this article useful. Thanks for reading.