As we discussed in previous post that in SRP there should never be more than one reason for a class to change.

That means, in SRP a reason to change is defined as a responsibility, therefore SRP states, “An object should have only one reason to change”. If an object has more than one reason to change then it has more than one responsibility and is in violation of SRP rule. An object should have one and only one reason to change.

Let’s look at an example. In the example below I have a BankAccount class that has a couple of methods in it:

public abstract class BankAccount {
     double Balance { get; }

     void Deposit(double amount) {}
     void Withdraw(double amount) {}
     void AddInterest(double amount) {}
     void Transfer(double amount, IBankAccount toAccount) {}
}

Let’s say that we use this BankAccount class for a person’s checking and savings account. That would cause this class to have more than two reasons to change. This is because checking accounts do not have interest added to them and only savings accounts have interest added to them on a monthly basis or however the bank calculates it.

Some people may argue that the class would even have 3 reasons to change because of the deposit/withdraw methods as well. But, I think you can definitely get a little crazy with SRP. That being said, I believe it just depends on the context.

Let’s refactor this to be more SRP friendly:

public abstract class BankAccount {
     double Balance { get; }

     public abstract void Deposit(double amount) {}
     public abstract void Withdraw(double amount) {}
     public abstract void Transfer(double amount, IBankAccount toAccount) {}
}

public class CheckingAccount: BankAccount {
     ...
}

public class SavingAccount: BankAccount {
     ...
     public void AddInterest(double amount) {}
}

So, what we have done is simply created an abstract class out of BankAccount class and then created a concrete CheckingAccount and SavingAccount classes so that we can isolate the methods that are causing more than one reason to change.

I’m sure you can come up with a lot more instances where you have violated SRP, and even instances where it just depends on the context.

The SRP is one of the simplest of the principle, and one of the hardest to get right