SOLID Principles - Part 1
The first two SOLID principles, Single Responsibility and Open/Closed, explained with fund report and fee calculation examples in C#, plus when not to apply them.
SOLID Principles - Part 1
In the previous article, we discussed why we need clean code, which provides a good overview of readability and small functions. Clean code at method level is a good start, but when the application is growing, we need principles at class and module level too, otherwise the classes are becoming big and tightly coupled. SOLID is the set of five design principles which helps us to design classes that are easy to change and easy to test. In this article, we are going to see the first two principles, Single Responsibility and Open/Closed, with real examples.
TL;DR Summary
- SOLID stands for Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion.
- These principles are introduced by Robert C. Martin (Uncle Bob).
- Single Responsibility Principle (SRP) - a class should have only one reason to change.
- Open/Closed Principle (OCP) - a class should be open for extension but closed for modification.
- SRP reduces the ripple effect of a change.
- OCP allows adding new behaviour without touching the tested code.
- Don’t apply the principles blindly, apply them where the change is really happening.
Challenges
Big classes that change for every reason
Most of the legacy projects have few classes like FundService or OrderManager which are doing everything, validation, database access, calculation, email and logging. Every new requirement is touching the same class. Multiple developers are editing the same file, merge conflicts are common and small change in email logic is breaking the calculation.
Switch statements everywhere
When a new type is introduced, i.e. a new fund type or a new payment method, the developer has to find all the switch statements and add one more case. Missing one place means a bug in production. And also, the already tested code is modified again and again, so the whole module needs to be tested again.
What is SOLID?
SOLID is an acronym for five object-oriented design principles,
- S - Single Responsibility Principle (SRP)
- O - Open/Closed Principle (OCP)
- L - Liskov Substitution Principle (LSP)
- I - Interface Segregation Principle (ISP)
- D - Dependency Inversion Principle (DIP)
In simple terms, these principles help us to keep the classes small, focused and loosely coupled, so that the change in one place doesn’t break other places.
Single Responsibility Principle (SRP)
A class should have one, and only one, reason to change.
Simply put, one class should do one job. The “reason to change” is the key here. If the business people from two different departments can ask you to change the same class for two different reasons, then that class has two responsibilities.
Think about a Swiss army knife. It is useful for a camping trip, but no chef is using it in the kitchen. When the blade is broken, you lose the scissors and the screwdriver also. Separate tools are easier to replace and improve.
Example - before
Let us take a fund report class from our domain,
public class FundReport
{
public decimal CalculateTotalValue(Fund fund)
{
return fund.Units * fund.UnitPrice;
}
public string GenerateHtml(Fund fund)
{
return "<h1>" + fund.Name + "</h1><p>" + CalculateTotalValue(fund) + "</p>";
}
public void SaveToDatabase(Fund fund)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Funds"].ConnectionString))
{
// insert report
}
}
}
This class has three reasons to change,
- the calculation rule is changed by the finance team.
- the report layout is changed by the marketing team.
- the database is changed by the IT team.
Example - after
public class FundValueCalculator
{
public decimal CalculateTotalValue(Fund fund)
{
return fund.Units * fund.UnitPrice;
}
}
public class FundReportFormatter
{
private readonly FundValueCalculator _calculator;
public FundReportFormatter(FundValueCalculator calculator)
{
_calculator = calculator;
}
public string GenerateHtml(Fund fund)
{
return "<h1>" + fund.Name + "</h1><p>" + _calculator.CalculateTotalValue(fund) + "</p>";
}
}
public class FundReportRepository
{
public void Save(Fund fund)
{
// insert report
}
}
Now each class has only one reason to change. When the layout is changed, the calculation is not touched at all, and it is easy to write unit tests for each class separately.
Note: SRP doesn’t mean one method per class. A class can have many methods, as long as all of them serve the same responsibility.
Open/Closed Principle (OCP)
Software entities (classes, modules, functions) should be open for extension, but closed for modification.
In simple terms, we should be able to add new behaviour without changing the existing code which is already tested and running in production. We achieve it with abstraction, i.e. interfaces, abstract classes and polymorphism.
Think about a power socket in your house. When you buy a new device, you don’t rewire the wall, you just plug it in. The socket is closed for modification, but open for any new device.
Example - before
Each fund type has a different management fee rule,
public class FeeCalculator
{
public decimal CalculateFee(Fund fund)
{
switch (fund.Type)
{
case FundType.Equity:
return fund.TotalValue * 0.015m;
case FundType.Bond:
return fund.TotalValue * 0.008m;
case FundType.MoneyMarket:
return fund.TotalValue * 0.002m;
default:
throw new NotSupportedException();
}
}
}
When the business introduces a new “Index” fund type, we have to open this class and modify it. It is the same story for every other switch on FundType in the code base.
Example - after
public interface IFeeRule
{
bool AppliesTo(FundType fundType);
decimal Calculate(Fund fund);
}
public class EquityFeeRule : IFeeRule
{
public bool AppliesTo(FundType fundType) { return fundType == FundType.Equity; }
public decimal Calculate(Fund fund) { return fund.TotalValue * 0.015m; }
}
public class BondFeeRule : IFeeRule
{
public bool AppliesTo(FundType fundType) { return fundType == FundType.Bond; }
public decimal Calculate(Fund fund) { return fund.TotalValue * 0.008m; }
}
public class FeeCalculator
{
private readonly IEnumerable<IFeeRule> _rules;
public FeeCalculator(IEnumerable<IFeeRule> rules)
{
_rules = rules;
}
public decimal CalculateFee(Fund fund)
{
return _rules.Single(r => r.AppliesTo(fund.Type)).Calculate(fund);
}
}
Now, adding the new “Index” fund type means adding one new class IndexFeeRule. The FeeCalculator is not modified, hence no need to test it again. The rules are injected through the constructor, we will see this in detail in an upcoming article on Dependency Injection.
Note: The fee percentages above are only for the example, they are not real fee rules.
When not to apply?
It is important to keep the balance here. If you apply SRP and OCP to every class from the first day, you will end up with hundreds of tiny classes and interfaces, which is also hard to read. Here are some few guidelines,
- Apply OCP when you see the same kind of change happening for the second or third time, not on the first.
- Apply SRP when a class is changing for more than one reason, or when it is hard to name the class without “And” or “Manager”.
- Simple CRUD screens may not need this level of abstraction.
It is a trade-off between flexibility and simplicity, and the right answer depends on how often that part of the code is changing.
Wrap up
In this article, we have looked at what is SOLID, the Single Responsibility Principle and the Open/Closed Principle with fund report and fee calculation examples. I appreciate your time and efforts to read this article. In the next article, I will walk you through the remaining three principles, Liskov Substitution, Interface Segregation and Dependency Inversion.
Related Posts
SOLID Principles - Part 2
The remaining SOLID principles, Liskov Substitution, Interface Segregation and Dependency Inversion, explained with practical examples from a fund domain and practical guidance.
How to use Dependency Injection with an IoC container in ASP.NET MVC?
Dependency Injection and IoC containers explained through Unity and Autofac setup in ASP.NET MVC 5, including object lifetimes and practical container wiring.
Why we need Clean Code?
Why clean code matters, what makes code clean (meaningful names, small functions, guard clauses, comments that explain why) and how to bring the practice into your team.