SOLID Principles, especially Liskov Substitution Principle with examples
EPAM · Role not specified · technical
Published
Year not specified · C#
Community answers
Posted by wasAsked editorial collection
The Liskov Substitution Principle says code using a base abstraction should continue to behave correctly when given any valid subtype. A subtype must honor the base contract: it should not demand stronger preconditions, promise weaker results, or introduce surprising failures.
A classic violation is a writable rectangle abstraction with a square subtype, because independently setting width and height conflicts with a square's invariant. Model capabilities honestly instead:
```csharp
public interface IShape
{
decimal Area { get; }
}
public sealed record Rectangle(decimal Width, decimal Height) : IShape
{
public decimal Area => Width * Height;
}
public sealed record Square(decimal Side) : IShape
{
public decimal Area => Side * Side;
}
static decimal TotalArea(IEnumerable<IShape> shapes) =>
shapes.Sum(shape => shape.Area);
```
Both implementations satisfy the read-only shape contract without pretending they support incompatible mutation. LSP is not “use inheritance”; it is a test of behavioral substitutability. Contract tests applied to every implementation are a practical way to detect violations.
Pooja Parmar · · 0 likes
SOLID is a set of five object-oriented design principles that make code easier to change, test and extend.
S — Single Responsibility Principle: a class should have one reason to change. Separate invoice calculation, persistence and PDF generation.
O — Open/Closed Principle: open for extension, closed for modification. Add a new discount type by adding a class implementing IDiscountRule, not by editing a growing switch statement.
L — Liskov Substitution Principle: subtypes must be substitutable for their base types without breaking behaviour. (Detailed below.)
I — Interface Segregation Principle: clients should not depend on methods they do not use. Split a fat IWorker { Work(); Eat(); } into IWorkable and IFeedable, so a Robot is not forced to implement Eat().
D — Dependency Inversion Principle: high-level modules depend on abstractions, not concrete implementations. OrderService depends on IOrderRepository; the SQL implementation is injected.
Liskov Substitution Principle in depth
If code works with a base type, it must keep working with any derived type. Derived classes must keep the base class's promises:
- Do not require more from callers (stronger preconditions).
- Do not deliver less (weaker postconditions).
- Keep the base class's invariants.
- Do not throw new, unexpected exceptions for supported operations.
Example 1 — read-only collection:
public class ReadOnlyList<T> : List<T>
{
public new void Add(T item) => throw new NotSupportedException();
}
Code accepting List<T> expects Add to work — and through a List<T> reference this "hidden" Add is not even called, so the design is both broken and confusing. Correct approach: implement IReadOnlyList<T> instead of inheriting List<T>.
Example 2 — file storage:
public interface IFileStore { Task SaveAsync(string path, Stream content); Task DeleteAsync(string path); }
public class ArchiveStore : IFileStore
{
public Task DeleteAsync(string path) => throw new InvalidOperationException("Archive is immutable");
}
Any cleanup job using IFileStore breaks for ArchiveStore. Fix with interface segregation: IFileWriter and IFileDeleter, so ArchiveStore implements only what it supports.
Example 3 — Rectangle and Square: a mutable Square that forces width and height to stay equal breaks code that sets them independently on a Rectangle.
How to spot LSP problems: NotSupportedException in overrides, empty overrides, type checks on base references, and tests that pass for the base type but fail for a subtype.