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.
SOLID Principles - Part 2
In the previous article, we discussed the Single Responsibility and Open/Closed principles, which helps us to keep the classes focused and extendable. In this article, we are going to see the remaining three principles, Liskov Substitution, Interface Segregation and Dependency Inversion. These three are mostly about how the classes are talking to each other through abstractions, and when we get them wrong, the abstractions are becoming a trap instead of a help.
TL;DR Summary
- Liskov Substitution Principle (LSP) - a derived class must be usable wherever its base class is expected, without surprises.
- If a subclass throws
NotImplementedExceptionfor a base method, it is a sign of LSP violation. - Interface Segregation Principle (ISP) - clients should not be forced to depend on methods they don’t use.
- Prefer small, role based interfaces over one fat interface.
- Dependency Inversion Principle (DIP) - high-level modules should depend on abstractions, not on low-level details.
- DIP makes the code testable and is the foundation for Dependency Injection.
Challenges
Inheritance that breaks the callers
Inheritance looks attractive for code reuse, but when the derived class changes the behaviour of the base class, the callers start to break in unexpected ways. The developer adds if (x is SpecialType) checks in the calling code and the polymorphism is lost.
Fat interfaces
Sometimes we create one big interface like IFundService with 25 methods, and every implementation has to implement all of them, even when it needs only two. Many methods are left with throw new NotImplementedException(), which will blow up only at runtime.
Hard-wired dependencies
When the business class creates its own SqlConnection, SmtpClient or HttpClient with the new keyword, we cannot test it without a real database or mail server. It also means, changing the database or the mail provider requires changing the business logic.
Liskov Substitution Principle (LSP)
Objects of a superclass should be replaceable with objects of its subclasses without breaking the correctness of the program.
In simple terms, if B is a subtype of A, then wherever the code is using A, we should be able to give B and it should behave as expected. The subclass can extend the behaviour, but it must not break the promise (contract) of the base class.
Think about a car rental. You booked “a car” and they gave you an electric car. You can still drive it, steer it and stop it, fine. But if they gave you a toy car which looks like a car but cannot drive, then your trip is broken. The toy car is not a valid substitute.
Example - violation
public class Fund
{
public virtual void Redeem(decimal units)
{
Units -= units;
}
public decimal Units { get; protected set; }
}
public class ClosedEndedFund : Fund
{
public override void Redeem(decimal units)
{
throw new InvalidOperationException("Closed-ended funds cannot be redeemed before maturity.");
}
}
Any code which loops through List<Fund> and calls Redeem will crash when it meets a ClosedEndedFund. The caller now needs to know the concrete type, which defeats the purpose of the base class.
Example - fix
Model the capability explicitly, instead of pretending all funds can be redeemed,
public abstract class Fund
{
public decimal Units { get; protected set; }
}
public interface IRedeemable
{
void Redeem(decimal units);
}
public class OpenEndedFund : Fund, IRedeemable
{
public void Redeem(decimal units)
{
Units -= units;
}
}
public class ClosedEndedFund : Fund
{
}
Now only the funds which can be redeemed are exposing Redeem, and the compiler will tell us when we use it wrongly, not the production server.
Here are some signs of LSP violation,
- override method throws
NotImplementedExceptionorNotSupportedException. - override method does nothing (empty body) where the base class does something meaningful.
- calling code checks the type with
isorasbefore calling a method. - subclass requires stronger input validation than the base class.
Interface Segregation Principle (ISP)
Clients should not be forced to depend upon interfaces that they do not use.
Simply put, many small interfaces are better than one big interface. Each interface should represent one role, and a class can implement as many roles as it needs.
Example - violation
public interface IFundService
{
Fund GetById(int id);
IEnumerable<Fund> Search(string keyword);
void Save(Fund fund);
void Delete(int id);
byte[] ExportToPdf(int id);
void SendFactsheetEmail(int id, string email);
}
The read-only fund search page needs only GetById and Search, but it depends on the whole interface. When the email method signature is changed, the search page is recompiled and redeployed. And also, a read-only cached implementation has to implement Save and Delete with exceptions.
Example - fix
public interface IFundReader
{
Fund GetById(int id);
IEnumerable<Fund> Search(string keyword);
}
public interface IFundWriter
{
void Save(Fund fund);
void Delete(int id);
}
public interface IFundFactsheetExporter
{
byte[] ExportToPdf(int id);
}
The search controller depends only on IFundReader. It is also easier to mock in unit tests, since you need to setup only the methods which are relevant.
Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details, details should depend on abstractions.
In simple terms, your business logic should not know whether the data is coming from SQL Server, a web service or a file. It should talk to an interface, and the concrete implementation is given from outside.
Again, the power socket analogy works well here. The lamp doesn’t depend on the power plant, both are depending on the standard socket. You can change the power provider without changing the lamp.
Example - violation
public class UnitPriceService
{
public decimal GetLatestPrice(int fundId)
{
var repository = new SqlUnitPriceRepository();
return repository.GetLatest(fundId);
}
}
UnitPriceService is tightly coupled with SqlUnitPriceRepository. We cannot unit test it without a database, and we cannot switch to a pricing web service without changing this class.
Example - fix
public interface IUnitPriceRepository
{
decimal GetLatest(int fundId);
}
public class UnitPriceService
{
private readonly IUnitPriceRepository _repository;
public UnitPriceService(IUnitPriceRepository repository)
{
_repository = repository;
}
public decimal GetLatestPrice(int fundId)
{
return _repository.GetLatest(fundId);
}
}
Now the dependency is inverted. The service owns the abstraction (IUnitPriceRepository) and the SQL implementation is a detail which plugs into it. In unit test, we can pass a mock, and in production, we pass the real repository.
Note: Dependency Inversion is the principle, Dependency Injection is the technique to implement it, and an IoC container is the tool which automates it. We will discuss how to use Dependency Injection with an IoC container in ASP.NET MVC in the upcoming article.
Putting all five together
Find below the quick summary of all five principles,
| Principle | One line | Smell when violated |
|---|---|---|
| SRP | One reason to change | Class name with “Manager”, “And”, very long files |
| OCP | Extend without modifying | Same switch on type in many places |
| LSP | Subtypes must keep the contract | NotImplementedException in overrides, type checks |
| ISP | Small role interfaces | Mocks with many unused setups, empty implementations |
| DIP | Depend on abstractions | new of infrastructure classes inside business logic |
Keep in mind that these are principles, not laws. Apply them where the code is really changing and where the testability matters, otherwise you will add abstractions which nobody needs.
Wrap up
In this article, we have looked at Liskov Substitution, Interface Segregation and Dependency Inversion principles with examples from the fund domain, and a summary table of all five SOLID principles. Thanks for reading this article. In the next article, I will walk you through how to use Dependency Injection with an IoC container in ASP.NET MVC.
Related Posts
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.
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.
Async and await in C# - common mistakes
Async and await explained for web applications, including I/O-bound work, async void, blocking calls, deadlocks, ConfigureAwait, fake async, and sequential awaits.