Volume 6 · Chapter 5 — Enterprise Application Architecture and Design Patterns
SOLID Principles in Large Systems
5.1 Introduction
SOLID is five object-oriented design principles that together push a codebase toward low coupling and high cohesion. In small programs they feel academic; in large, long-lived .NET systems maintained by rotating teams they are what keep change local and safe. The principles are not laws to be maximised - over-applied they produce needless indirection - but a lens for spotting designs that will be painful to change.
5.2 Single Responsibility Principle (SRP)
A class should have one reason to change. The common misreading is “a class should do one thing”; the sharper version is that a class should answer to a single actor or axis of change. When a class mixes persistence, business rules, and notification, a change requested by any one of those concerns risks breaking the others.
// Violates SRP: business rule, persistence, and email all in one class.
public class OrderService
{
public void Place(Order o)
{
if (o.Total <= 0) throw new Exception(); // rule
_db.Save(o); // persistence
_smtp.Send(o.Email, "Order placed"); // notification
}
}
// Respects SRP: each responsibility can change independently.
public class PlaceOrderHandler
{
public async Task Handle(PlaceOrder cmd)
{
var order = Order.Create(cmd.Lines); // domain enforces the rule
_repository.Add(order); // persistence behind a port
await _uow.SaveChangesAsync();
_events.Raise(new OrderPlaced(order.Id)); // notification via event
}
}
5.3 Open/Closed Principle (OCP)
Software entities should be open for extension but closed for modification. New behaviour should arrive through new code - a new strategy, a new handler, a new implementation of an interface - rather than by editing stable, tested classes. Strategy, Decorator, and polymorphic dispatch are the everyday mechanisms.
5.4 Liskov Substitution Principle (LSP)
Subtypes must be usable anywhere their base type is expected, without surprising the caller. Violations include a subclass that throws on a method the base supports, strengthens preconditions, or weakens postconditions. The classic example is aSquarederiving fromRectangleand breaking code that sets width and height independently.
5.5 Interface Segregation Principle (ISP)
Clients should not be forced to depend on methods they do not use. Fat interfaces couple unrelated consumers and force empty or throwing implementations. Splitting a largeIRepositoryinto focused capabilities keeps each consumer honest.
// Fat interface forces every implementer to support everything.
public interface IRepository<T>
{
Task<T?> GetAsync(Guid id);
Task<IReadOnlyList<T>> ListAsync();
void Add(T entity);
void Remove(T entity);
Task BulkImportAsync(Stream csv); // not everyone needs this
}
// Segregated: read and write and import evolve independently.
public interface IReader<T> { Task<T?> GetAsync(Guid id); }
public interface IWriter<T> { void Add(T e); void Remove(T e); }
public interface IBulkImporter<T> { Task ImportAsync(Stream csv); }
5.6 Dependency Inversion Principle (DIP)
High-level policy should not depend on low-level detail; both should depend on abstractions. This is the principle behind Clean Architecture’s ports and adapters and behind .NET’s built-in dependency injection. The business service depends onIEmailSender; the SMTP implementation depends on that same abstraction; neither the policy nor the detail depends on the other directly.
flowchart TB HL["High-level: NotificationService"] --> ABS["IEmailSender (abstraction)"] LL["Low-level: SmtpEmailSender"] --> ABS
5.7 SOLID and .NET Dependency Injection
The built-in container makes DIP and OCP natural: services declare their dependencies as interface parameters, and the composition root binds them. Swap an implementation for a test double or a new provider without touching the consumer.
5.8 Refactoring Legacy Code Toward SOLID
Large systems accumulate debt. SOLID guides safe, incremental refactoring: identify a class with several reasons to change, extract collaborators behind interfaces, add characterization tests to lock in behaviour, then restructure. The goal is to make the next change easier, not to achieve theoretical purity in one heroic sweep.
sequenceDiagram autonumber participant Dev as Engineer participant Test as Characterization Tests participant Legacy as God Class participant New as Extracted Services Dev->>Test: write tests capturing current behaviour Test-->>Dev: green (safety net) Dev->>Legacy: extract responsibilities behind interfaces Legacy->>New: delegate to focused services Dev->>Test: re-run Test-->>Dev: still green (behaviour preserved)
Is following SOLID always required?
No - SOLID is a set of heuristics, not mandates. Each principle trades some simplicity now for changeability later, and that trade is only worth it where change is likely. Blindly applying SOLID produces interface-per-class ceremony and indirection that obscures intent. The skill is judgment: apply the principles where a design is genuinely brittle or a concern genuinely volatile, and accept simpler, more direct code where it is not.
Give a concrete example of a Liskov Substitution violation and how you would fix it.
AReadOnlyListthat inherits from a mutableListbut throwsNotSupportedExceptiononAddviolates LSP: callers written againstListbreak when handed the subtype. The fix is to correct the hierarchy so the “is-a” relationship holds behaviourally - introduce a read-only interface (IReadOnlyList<T>) that the mutable type also implements, and program callers to the capability they actually need rather than to the fat mutable base. Favour composition and narrow interfaces over inheritance that promises more than the subtype can deliver.
How does the Interface Segregation Principle relate to microservices?
ISP scales up from methods to service contracts. A service that exposes one bloated API forces every consumer to couple to the whole surface, so any change risks all of them. Segregating capabilities - separate endpoints or even separate services per client need, or a Backend-for-Frontend tailored to each consumer - keeps clients depending only on what they use. The same instinct that splits a fat C# interface splits an over-general API into focused, independently evolvable contracts.
How do SOLID principles help large enterprise systems specifically?
At scale, the dominant cost is change under uncertainty across many teams. SOLID attacks that directly: SRP and ISP keep changes local so a team can modify one concern without rippling into others; OCP and DIP let new behaviour and new integrations be added without editing shared, high-risk code; LSP keeps polymorphic substitution safe so abstractions can be trusted. The net effect is that the blast radius of a change shrinks, tests stay meaningful, and independent teams can move in parallel - which is exactly what large systems need.
A codebase is "SOLID" but nobody can find anything and simple changes touch ten files. What went wrong?
This is over-abstraction masquerading as good design - principles applied as dogma rather than judgment. Symptoms include an interface for every class with a single implementation, excessive layering and mapping, and indirection that spreads one logical change across many files. The problem is that the abstractions do not correspond to real axes of variation; they add cost without optionality. I’d collapse single-implementation interfaces, inline needless layers, and re-introduce abstractions only where variation actually exists. Good architecture minimises the total cost of change, which includes the cost of understanding the code, not just the cost of extending it.
5.9 Banking Enterprise Scenario
A bank’s transaction service began as a single class handling validation, persistence, fee calculation, and notifications - every regulatory tweak risked unrelated breakage. Guided by SOLID, the team extracted a domain model that owns the rules (SRP), put persistence behind repository interfaces (DIP), expressed new fee schemes as strategies added without editing existing code (OCP), split a fat repository interface into read/write capabilities (ISP), and ensured every account subtype honoured its base contract (LSP). Change velocity and test reliability both improved measurably.
Chapter Revision Notes
- SRP: one reason (actor) to change per class.
- OCP: extend via new code, not edits to stable classes.
- LSP: subtypes must honour the base type’s behavioural contract.
- ISP: prefer several focused interfaces over one fat one.
- DIP: depend on abstractions; the composition root binds detail.
- Apply SOLID by judgment - over-application causes its own problems.