solid-principles Single Responsibility Principle (SRP) Single Responsibility Principle C#


Example

Let's go through the problem first. Have a look on the code below:

public class BankAccount
{             
    public BankAccount()  {}

    public string AccountNumber { get; set; }
    public decimal AccountBalance { get; set; }

    public decimal CalculateInterest()
    {
        // Code to calculate Interest
    }
}

Here, BankAccount class contains the properties of account and also calculate the interest of account. Now look at the few change Request we received from business:

  1. Please add a new Property AccountHolderName .
  2. Some new rule has been introduced to calculate interest.

This are totally different type of change request. One is changing on features; where as other one is impacting the functionality. We have 2 different types of reason to change one class. This violates Single Responsibility Principle.

Now let's try to implement SRP to resolved this violation. Look at the code below:

public interface IBankAccount
{
    string AccountNumber { get; set; }
    decimal AccountBalance { get; set; }
}

public interface IInterstCalculator
{
    decimal CalculateInterest();
}

public class BankAccount : IBankAccount
{
    public string AccountNumber { get; set; }
    public decimal AccountBalance { get; set; }
}

public class InterstCalculator : IInterstCalculator
{
    public decimal CalculateInterest(IBankAccount account)
    {
        // Write your logic here
        return 1000;
    }
}

Now our BankAccount class is just responsible for properties of the bank account. If we want to add any new business rule for the Calculation of Interest, we don't need to change BankAccount class.

And also InterestCalculator class requires no changes, in case we need to add a new Property AccountHolderName. So this is the implementation of Single Responsibility Principle.

We have also used Interfaces to communicate between InterestCalculator and BankAccount class. This will help us to manage dependencies between classes.