Saturday 14 May 2016

Single Responsibility Principle (SRP)

There should never be more than one reason for change anything in software entities (class, function, file etc). A class, function, file etc should have only one reason to change. Let's go through the problem first. Have a look at the code given 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.

No comments:

Post a Comment