Search Sreeni's Insights

Filter by content type
technical February 7, 2012 6 min read

What are the Single Responsibility and Open Closed principles? - Part 3

The Single Responsibility and Open Closed principles are explained with a mutual fund service and exit load rules, with the benefits, techniques and trade-offs of each.

Share:

What are the Single Responsibility and Open Closed principles? - Part 3

Every system has a part which everybody is afraid to change, and in most cases it is one big class which started small. In the previous article, we discussed the basic guidelines, Tell Don’t Ask and the Law of Demeter. Now we are entering the five design principles called as SOLID, which was popularized by Robert C. Martin. The five letters stand for Single Responsibility, Open Closed, Liskov Substitution, Interface Segregation and Dependency Inversion principles. In this article, we are going to see the first two, how a class should have only one reason to change, and how new requirements should be added without editing the old and tested code.

Maintainable Code series:

  1. Why does code become hard to maintain? - Part 1
  2. How to keep the code simple and the objects in charge? - Part 2
  3. What are the Single Responsibility and Open Closed principles? - Part 3 (this article)
  4. What are the Liskov Substitution and Interface Segregation principles? - Part 4
  5. How to use Dependency Inversion to loosen the coupling? - Part 5

TL;DR Summary

  • Single Responsibility Principle (SRP) - A class should have only one reason to change.
  • A responsibility is a reason to change. If two different people can ask you to change the class for different reasons, it has two responsibilities.
  • Open Closed Principle (OCP) - A class should be open for extension and closed for modification.
  • SRP gives high cohesion and low coupling. OCP lowers the risk of regression, because the old code is not touched.
  • Techniques - Abstraction, Decorator and Composite for SRP, and Inheritance, Polymorphism and Strategy for OCP.
  • Don’t apply them for every class on day one, apply them where the change is really coming (YAGNI).

Single Responsibility Principle

What is it?

The Single Responsibility Principle says, a class or a module should exist for only one reason to change. Here, a responsibility is nothing but a reason to change. It is closely related to the cohesion we discussed in Part 1, a class which does one thing has all of its members working together.

Example

Find below a typical FundService which grew over the time,

public class FundService
{
    public decimal CalculateNav(Fund fund) { /* ... */ }
    public decimal ApplyExpenseRatio(Fund fund, decimal nav) { /* ... */ }
    public string GenerateStatement(Folio folio) { /* ... */ }
    public void SendNavEmail(Fund fund, decimal nav) { /* ... */ }
    public void Save(Fund fund) { /* SQL insert and update */ }
}

Let us ask who can request a change to this class,

  • The fund accountant changes the NAV or the expense ratio rule.
  • The marketing team changes the statement layout.
  • The operations team changes the email template or the mail server.
  • The DBA changes the table structure.

That is four different groups of people, and five responsibilities in one class, because the NAV and the expense ratio change for the same accountant but they are still two different rules. The following diagram shows the class before and after the split.

One class with five reasons to change vs one reason each
One class with five reasons to change vs one reason each
public class NavCalculator       { public decimal Calculate(Fund fund) { /* ... */ } }
public class FeeCalculator       { public decimal Apply(Fund fund, decimal nav) { /* ... */ } }
public class StatementGenerator  { public string Generate(Folio folio) { /* ... */ } }
public class EmailNotifier       { public void Send(Fund fund, decimal nav) { /* ... */ } }
public class FundRepository      { public void Save(Fund fund) { /* ... */ } }

The FundService is not removed, it becomes a thin coordinator which tells the others what to do (Tell Don’t Ask again). The statement layout change now touches only the StatementGenerator, and the NAV tests don’t need a mail server anymore.

Benefits

  • High cohesion and low coupling.
  • Easier to understand, each class is small and has a clear name.
  • Reusability, the NavCalculator can be used by the website and the batch process.
  • Easy testing.

Techniques

  • Abstraction and Encapsulation, to find the right boundary and hide the details.
  • Decorator pattern, to add a cross-cutting behavior like logging or auditing around a class without changing it.
  • Composite pattern, to treat a group of objects as one, for example many fee components calculated as one fee.
  • KISS, don’t split so much that nobody can follow the flow.

Must Be Aware: A class named ”…Manager”, ”…Helper” or a class whose description needs the word “and” is a candidate for a split. But too many tiny classes with one method each also make the code hard to follow. Split along the reasons to change which are real, not the imaginary ones.

Open Closed Principle

What is it?

The Open Closed Principle says, a class or a component should be open for extension and closed for modification. It means, we should be able to add new behavior without editing the code which already works and is already tested. The idea was introduced by Bertrand Meyer and later restated by Robert C. Martin with the polymorphism.

Example

Let us continue the exit load. Initially there was only one rule, then every fund type got its own. The easiest code is a switch,

public class ExitLoadCalculator
{
    public decimal Calculate(Fund fund, decimal amount, int holdingDays)
    {
        switch (fund.Type)
        {
            case FundType.Equity:
                return holdingDays < 365 ? amount * 0.01m : 0m;
            case FundType.Debt:
                return holdingDays < 90 ? amount * 0.005m : 0m;
            case FundType.Liquid:
                return 0m;
            default:
                throw new NotSupportedException();
        }
    }
}

Note: The percentages and periods here are only examples to explain the design, they are not the real rules of any fund house.

Now the fund house launches the Fixed Maturity Plan (FMP) with its own exit load. We must open the calculator, add a new case and test every old case again, because the same method is changed. If anybody makes a mistake in the new case, the old funds are affected. It is exactly the regression risk we want to avoid.

The fix is to move the variation behind an abstraction, and let the calculator depend on it,

public interface IExitLoadRule
{
    bool AppliesTo(Fund fund);
    decimal Calculate(decimal amount, int holdingDays);
}

public class EquityFundRule : IExitLoadRule
{
    public bool AppliesTo(Fund fund) { return fund.Type == FundType.Equity; }
    public decimal Calculate(decimal amount, int holdingDays)
    {
        return holdingDays < 365 ? amount * 0.01m : 0m;
    }
}

public class ExitLoadCalculator
{
    private readonly IEnumerable<IExitLoadRule> _rules;

    public ExitLoadCalculator(IEnumerable<IExitLoadRule> rules) { _rules = rules; }

    public decimal Calculate(Fund fund, decimal amount, int holdingDays)
    {
        return _rules.First(r => r.AppliesTo(fund)).Calculate(amount, holdingDays);
    }
}

The following diagram depicts the structure.

Open for extension, closed for modification
Open for extension, closed for modification

For the new fund type, we add one new class, FixedMaturityRule, and give it to the calculator. The calculator and the other rules are not touched. It is closed for modification and open for extension.

Benefits

  • Easy to change, and the cost of a new rule is low.
  • Minimizes the risk of regression, because the tested code stays as it is.
  • Reusability and easy testing, each rule is tested alone.

Techniques

  • Inheritance and the Template Method pattern, when the steps are same and only one step varies.
  • Polymorphism, as in the example above.
  • Composition and the Strategy pattern, when the behavior should be selected or changed at runtime.
  • Visitor pattern, when we want to add new operations to a set of classes which are stable.

Must Consider: You can’t close a class against every kind of change. Choose the changes which are likely, for example new fund types, and close the code against those. Wait for the first change to show you the direction, and then apply OCP. If you do it for every class in advance, you break YAGNI and make the code complex.

SRP and OCP working together

SRP gives us small classes with one reason to change, and OCP tells how those classes should grow. In our example, the ExitLoadCalculator has one job (SRP), and each rule class has one job and is added without editing the calculator (OCP). If a class is hard to close for modification, most of the time it has more than one responsibility.

Wrap up

In this article, we have looked at the Single Responsibility Principle and the Open Closed Principle with a mutual fund example, their benefits and the techniques to apply them. I really appreciate that you took the time to read this article. In the next article, I will walk you through the Liskov Substitution Principle and the Interface Segregation Principle, which tell us how to design the inheritance and the interfaces properly.

Related Posts