What Are SOLID Principles - and When Applying Them Makes Your Code Worse

SOLID principles are five design guidelines for object-oriented code, each one a different answer to the same question: when this code has to change, how much of it do you have to touch? The name is an acronym - Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion - collected by Robert C. Martin from ideas that were already circulating in the 1990s.

They exist because of a specific failure mode. A class starts small, accumulates responsibilities, and eventually every change to it risks breaking something unrelated. Tests get slow because the class needs a database to instantiate. Two teams edit the same file for unrelated reasons. SOLID is a set of heuristics for arranging code so that the things that change together live together, and the things that change independently can be swapped.

They are heuristics, not theorems. Four of the five are judgement calls with no objective test for compliance; only Liskov Substitution has something close to a formal definition. That is worth knowing before someone blocks your pull request for "violating SRP". Two business professionals planning and discussing strategy at a whiteboard in a modern office setting.

ConceptSOLID principles (SRP, OCP, LSP, ISP, DIP)
Where it sitsDesign practice - sits at the class and module boundary layer, inside a single codebase
In one sentenceFive object-oriented design heuristics about where to draw boundaries so that a change lands in one place instead of twenty.

The 60-Second Answer

What it does: gives you five named heuristics for deciding where class and interface boundaries go - one responsibility per class, extend rather than edit, subtypes that honour their base contract, narrow interfaces, and dependencies pointing at abstractions rather than concrete implementations.

The one problem it solves: change amplification. Without boundaries, one requirement change ripples through unrelated code, and you cannot test a unit without standing up its whole dependency tree.

The one cost it adds: indirection. Every abstraction you introduce is a layer someone has to read through to answer "what actually runs here?" Applied to code that is not changing, SOLID buys you nothing and costs you the jump-to-definition chain.

How It Actually Works

1. Single Responsibility: one reason to change per class

Group by who asks for the change

The useful framing of SRP is not "a class should do one thing" - that is unfalsifiable, since any behaviour can be decomposed further. The sharper version is that a class should have one source of change requests. If the finance team's reporting rules and the ops team's export format both live in Invoice, two groups with different schedules are editing the same file.

So the test is social, not structural: look at the last ten changes to the class and ask who requested each one. If the answers come from different roles, the class is holding unrelated reasons to change.

# Two actors, one class: finance owns the calculation,
# ops owns the wire format.
class Invoice:
    def total_with_tax(self): ...   # finance
    def to_edi_record(self): ...    # ops

⚠️ In production — Splitting on SRP routinely produces classes that need each other's data, and people resolve that by adding getters until the "split" classes are coupled through their fields anyway. You moved the coupling from one file to two and made it harder to see. If the split needs five new accessors, the responsibility was not actually separable.


2. Open/Closed: add a case without editing the dispatcher

New behaviour by addition, not modification

OCP says a module should be open to extension and closed to modification: you should be able to add a new payment method or a new export format without editing the code that already works. In practice that means replacing a growing conditional with a polymorphic lookup - a registry, a strategy map, a set of handler classes.

The mechanism is simple: the caller depends on an abstract operation, and new concrete types register themselves. The dispatcher never changes, so you cannot break the existing branches while adding a new one.

HANDLERS = {}

def handler(kind):
    def wrap(cls):
        HANDLERS[kind] = cls
        return cls
    return wrap

# adding a format = new file, no edit to the dispatch site

⚠️ In production — OCP only pays off along the axis you guessed correctly. If you build extension points for new payment types and the actual requirement turns out to be new currencies, you now have to modify every handler - and the registry indirection makes that refactor harder than a switch statement would have been. You get one cheap axis of variation per abstraction, and you are guessing which one.


3. Liskov Substitution: a subtype cannot narrow the contract

The only one with a real definition

LSP is the one principle with teeth. If code works with a base type, it must keep working when handed any subtype. Formally, a subtype may weaken preconditions and strengthen postconditions, never the reverse. Throwing NotImplementedError from an override is the obvious violation; the subtle ones are tightening an accepted input range or changing what the method guarantees afterwards.

The classic failure is ReadOnlyList extends List, where append throws. Every caller that received a List and reasonably appended to it now breaks at runtime, and the type system told them it was fine.

// LSP violation: narrower precondition than the base
class Rect        { void setWidth(int w) { ... } }
class Square extends Rect {
  void setWidth(int w) { this.w = this.h = w; }  // breaks
}                                                 // callers that
                                                  // set w and h

⚠️ In production — LSP violations do not fail at compile time and usually do not fail in the subtype's own tests - the subtype tests only its own behaviour. They surface in production, in a caller written against the base type by someone who never read the subclass. The practical defence is a shared contract test suite run against every implementation, not code review.


4. Interface Segregation: clients should not depend on methods they ignore

Narrow interfaces, split by consumer

ISP says an interface should be shaped by what a specific caller needs, not by everything the implementation can do. A fat Repository interface with twenty methods forces every consumer to depend on all twenty - which means every test double must stub twenty methods, and every added method breaks every implementer.

The mechanism is to define the interface at the consumer's boundary, as narrowly as the consumer uses it. One implementation can satisfy several small interfaces at once.

// the consumer declares what it needs, not what exists
type UserFinder interface {
    FindByID(id string) (*User, error)
}

⚠️ In production — Taken too far, ISP produces a swarm of single-method interfaces with names nobody can keep straight, and finding which concrete type implements which becomes a grep exercise. The usual signal that you have gone too far: interfaces named after the method rather than the role. Split when a second consumer wants a different subset, not pre-emptively.


5. Dependency Inversion: the policy owns the interface

Point dependencies at abstractions

DIP says both high-level policy and low-level detail should depend on an abstraction, and critically, the abstraction should be owned by the policy layer. Your order service defines the PaymentGateway interface it needs; the Stripe adapter implements it. The dependency arrow now points from infrastructure toward business logic, which is the inversion.

This is what makes a unit test possible without a network. The policy code never names a concrete implementation, so the composition root - main, a DI container, a factory - decides at startup which one gets wired in.

class OrderService:
    def __init__(self, gateway: PaymentGateway):  # injected
        self._gateway = gateway

⚠️ In production — The failure mode is an interface that is a 1:1 mirror of one concrete class, with the vendor's vocabulary leaking through it - charge(idempotency_key, payment_method_token). That is not an abstraction, it is an alias, and swapping implementations will still require rewriting callers. An interface that has had exactly one implementation for two years is carrying no weight.


6. The composition root pays the assembly cost

Where all the wiring lands

Once dependencies point at abstractions, somebody has to choose the concrete objects. That job concentrates in a single composition root at the entry point, where the object graph is constructed and passed down. This is a deliberate trade: you have made the rest of the codebase ignorant of concrete types by making one place know all of them.

The root is allowed to be ugly and procedural. It is the only part of the system that is supposed to know everything.

⚠️ In production — In production the composition root becomes the thing nobody wants to touch, especially with a reflection-based DI container doing the wiring. Misconfiguration moves from a compile error to a startup error - or worse, a lazily resolved failure that only appears when a rarely-used code path first runs. Prefer explicit construction over container magic until the graph is genuinely too large to write by hand.


7. The five principles pull against each other

SRP and ISP push apart, cohesion pushes back

SRP and ISP push toward more, smaller units. OCP and DIP add indirection on top. Nothing in SOLID pushes back toward fewer pieces - that pressure has to come from you, usually framed as cohesion or locality of behaviour.

This is why SOLID as a checklist fails. The principles describe forces, and the design is where you balance them. A codebase that maximally satisfies all five is typically unreadable: dozens of one-method classes, every call site an interface, and no single file that tells you what the system does.

⚠️ In production — The giveaway in review is someone citing a principle name as the whole argument. "This violates SRP" is not a finding; "these two methods change on different release schedules and we keep merge-conflicting here" is. Ask for the observed cost before accepting a SOLID-shaped refactor.

Artistic black doodles on white paper, featuring arrows and nature elements. ## Where You Meet It
  • A payments service that started with a single provider and now supports three. The order code depends on a PaymentGateway interface it defines itself (DIP), each provider is an adapter behind it, and adding a fourth means adding a file rather than editing the checkout flow (OCP). This is the scenario SOLID was shaped for: a known axis of variation that has already varied.
  • A notification module where EmailSender, SmsSender, and PushSender all implement send(message). The SMS one silently truncates bodies over the carrier limit while the email one does not - an LSP violation that surfaces as a support ticket about half-sent messages, not as a test failure. The fix is a contract test suite that every sender must pass.
  • A test suite that takes eight minutes because instantiating the service layer opens a database connection and an HTTP client. Applying DIP at the service boundary - constructor-injected ports instead of imported concrete clients - is what moves those tests from integration to unit. The speedup is the measurable payoff, and it is usually the honest reason to do it.
  • A legacy UserManager that handles authentication, profile edits, and the GDPR export. Three teams open pull requests against it in the same sprint and spend their time on merge conflicts rather than features. The SRP split here is justified by the conflict rate, not by the class being large.
  • A plugin architecture - editor extensions, CI build steps, webhook handlers - where third parties supply implementations you never see. Here OCP and LSP are not optional style preferences: the published interface is a contract with people who cannot patch your dispatcher, and a subtype that breaks the contract breaks their code, not yours.

When You Actually Need It

  • The same file shows up in merge conflicts across multiple teams or feature streams - that is SRP pointing at a real boundary, with evidence.
  • You have already added the third implementation of something behind a conditional, so the axis of variation is observed rather than predicted, and OCP has a known direction to aim at.
  • Your unit tests require a database, a queue, or a network call to construct the object under test, and suite time or flakiness is hurting. DIP at that boundary is the direct fix.
  • You are publishing an interface that code outside your repository implements - a plugin API, an SDK, an internal library with external consumers. LSP and ISP become contractual obligations once you cannot see or fix all implementers.
  • A bug fix in one feature keeps breaking an unrelated feature, and the postmortems trace back to shared mutable state inside one class.
  • You are onboarding people into a module and they cannot tell which part owns a decision - the boundaries are missing, not just unlabelled.

When You Don't

  • A script, a one-off migration, or a tool that will run a handful of times. Procedural top-to-bottom code is correct here. A 200-line script you can read in one pass is more maintainable than six collaborating classes doing the same work, and no abstraction survives contact with code you delete next month.
  • A CRUD endpoint that maps a request to a table and back. If the handler has no branching business rules, a repository interface with one implementation and an injected service is pure ceremony. Write the query in the handler; extract later when a second caller or a second data source actually appears.
  • Before you know the axis of variation. Guessing wrong at extension points is worse than having none, because the wrong abstraction has to be dismantled before the real change can land. Write the conditional, let it grow to three branches, then extract - the duplication tells you where the seam is.
  • A small team on a small codebase where everyone can read the whole thing. Below roughly the point where one person can hold a module in their head, boundaries cost more in navigation than they save in isolation. Concretely: a few thousand lines, one or two people, one deploy unit - keep it flat and direct.
  • Code that has not changed in a year. SOLID buys cheap change. Stable code does not need cheap change, so refactoring it for principle compliance is spending review time and merge risk for no return. Leave it alone and point the effort at the file with the highest churn.
  • Languages and paradigms where the mechanisms do not translate. In a functional codebase, a function passed as an argument already gives you DIP and OCP without a class hierarchy, and in Go or Rust, structural interfaces and traits change the shape of ISP. Apply the underlying force - put the decision where change happens - not the class-based recipe. A programmer working on code with a laptop and monitor setup in an office.

What People Get Wrong

"SOLID means every class gets an interface."

DIP asks for a dependency on an abstraction at boundaries you need to vary or test in isolation - typically I/O, external services, and published APIs. An interface with one permanent implementation adds a navigation hop and no substitutability. If you cannot name the second implementation or the test double that justifies it, it is not inversion.

"Single Responsibility means a class should do only one thing."

"One thing" has no stable granularity - any method can be split into two. Martin's own later framing is one actor, one reason to change. The operational version is: if two different stakeholders request changes to this class on different schedules, split it. If one does, leave it alone regardless of method count.

"SOLID code is automatically testable code."

DIP makes isolation possible; it does not make the tests meaningful. Heavy mocking of injected interfaces produces tests that assert your implementation calls the methods you wrote, and they pass while the integration is broken. Testability comes from a clean boundary plus contract tests against real implementations, not from injection alone.

"These are principles, so violating one is a defect."

Four of the five have no objective compliance test, and they pull in opposite directions - SRP and ISP toward fragmentation, cohesion and readability toward consolidation. They are forces to weigh, not rules to pass. The only one with a formal definition, and a real correctness consequence, is Liskov Substitution.

Why It Was Built This Way

SOLID was assembled under a constraint most of us no longer feel: in the 1990s, recompiling and relinking a large C++ program could take hours, and physical dependencies in header files decided what got rebuilt. If your high-level business logic #included a concrete database class, every change to that database header forced a rebuild and a redeploy of everything above it. Dependency Inversion was originally a build-time argument as much as a design one - putting an abstract class between policy and detail cut the physical dependency and the rebuild with it. Open/Closed was partly about not re-testing and re-shipping a module you had already certified.

What got traded away was locality. Every one of these principles takes something that was in one place and puts it in two or more, connected by a name rather than by a call you can follow. That was a good trade when the cost of touching a file was measured in build hours and the cost of reading was measured in a developer's attention - attention being abundant and compilers being slow. Modern tooling flipped the economics: builds are incremental, deploys are minutes, but reading a call chain through four interfaces to find the one line that matters is still as expensive as it ever was. Indirection has gone from nearly free to the dominant cost.

That is the thing to keep. SOLID is not a definition of good code; it is a set of techniques for buying cheap change at the cost of indirection, priced for a build system that no longer exists. The underlying forces are real and permanent - change amplification is still the thing that kills codebases - but the exchange rate moved. So apply each principle where you have evidence that change is actually happening, and resist it where the code is stable. A codebase where every abstraction is load-bearing is better than one where every principle is satisfied.

Related Briefs

What to Read Next

  • dependency injection vs dependency inversion
  • when to use the strategy pattern
  • hexagonal architecture explained

SOLID is a toolkit for making change cheap in the specific places where change keeps happening, and every application of it charges you indirection up front. So let churn, merge conflicts, and slow tests tell you where to apply it, rather than applying it uniformly and hoping. Liskov Substitution is the one to treat as a hard rule, because breaking it breaks callers you will never see; the other four are arguments you should be able to make with evidence from your own repository. If you cannot name the change the abstraction is making cheaper, you have not bought anything.

댓글

이 블로그의 인기 게시물

What Is a Message Queue - and When You Actually Don't Need One

What Is a Bloom Filter - and When You Actually Don't Need One

When to Use GraphQL Over REST API - and When REST Is Still the Right Call