SOLID is five design principles about classes and the dependencies between them: Single responsibility, Open/closed, Liskov substitution, Interface segregation and Dependency inversion. Each one names a way object-oriented code becomes rigid or fragile, and the habit that prevents it. They are the shared vocabulary of low-level design interviews and code reviews, and the reasoning behind many patterns in this track. This lesson states each principle precisely, runs a before-and-after for each one in the visualizer, and covers how each is misread or overused.
Think of it like
A restaurant kitchen
Each station has one job, so the pastry chef can change the desserts without touching the grill (single responsibility). A new dish is a new recipe card, not a rebuilt kitchen (open/closed). Any cook who covers the fry station must really be able to fry, or the orders that depend on it fail (Liskov substitution). The dishwasher gets the dishwashing checklist, not the full chef's manual (interface segregation). And the kitchen writes its own spec, "ripe tomatoes, delivered by 7 am", which any supplier can meet; the kitchen does not reorganize itself around one supplier's catalog (dependency inversion).
Five principles, one goal
Robert C. Martin wrote about these principles in articles and books from the mid-1990s on, including his 2000 paper Design Principles and Design Patterns; Michael Feathers later arranged five of them into the acronym SOLID. Two are older than the acronym: open/closed comes from Bertrand Meyer (1988) and substitution from Barbara Liskov (1987). All five are about dependencies: which code knows about which other code, and so what must change when something changes. Martin's paper names the symptoms they fight: rigidity (one change forces many), fragility (a change breaks unrelated places) and immobility (code cannot be reused elsewhere).
| Principle | In one sentence | Smell it targets | Usual fix |
|---|---|---|---|
| Single responsibility (SRP) | A module should have one reason to change. | A class that several groups of people keep editing for unrelated reasons | Split it along those reasons |
| Open/closed (OCP) | Open for extension, closed for modification. | A switch on a type that grows with every new case | Polymorphism: a new variant is a new class |
| Liskov substitution (LSP) | Subtypes must be usable wherever their base type is expected. | Overrides that throw, do nothing, or need instanceof checks | Honor the base contract, or do not inherit |
| Interface segregation (ISP) | Clients should not be forced to depend on methods they do not use. | Fat interfaces and stub methods | Small role interfaces |
| Dependency inversion (DIP) | Depend on abstractions, not on concrete details. | Business logic that creates its own database or HTTP client | An interface owned by the policy, implemented by the detail, injected |
Using the visualizer
The visualizer at the top of the page holds five scenarios. Choose a principle with the SRP, OCP, LSP, ISP, DIP buttons. Each scenario has its own Before and With SRP (or OCP, and so on) toggle, and four of them have a change-request button that makes the same change to both versions. Press Play or step with the arrow keys. Choosing another principle starts it on its With version with the change request off. When a change request is applied, badges on the class diagram and the side panel count the classes each version had to edit.
| Principle | Before | With the principle | Change request (Before / With) |
|---|---|---|---|
| SRP | Invoice totals, prints and saves itself | One class per reason to change | Dollar sign: 1 / 1, but Before also changes the saved row |
| OCP | A switch on each rule's kind | A Rule interface, one class per rule | Coupon: 2 / 0 (both versions add the rule) |
| LSP | Square extends Rectangle | Both implement Shape | None: the Before run itself fails |
| ISP | One fat Machine interface | Printer and Scanner roles | scanPdf(): 3 / 2 |
| DIP | OrderService creates MySqlStore | OrderService owns OrderStore | In-memory store: 1 / 0 (both add MemoryStore) |
S: single responsibility
Martin's original wording is "a class should have only one reason to change". In Clean Architecture (2017) he made it sharper: a module should be responsible to one, and only one, actor, where an actor is a group of people who ask for changes (finance, the customer-facing team, operations). Responsibility means a source of change, not a task. Ask who would request a change to each method: in the visualizer's Invoice, finance owns total(), the people who design the customer's invoice own print(), and accounting owns the format save() writes. Three actors in one class means their changes collide.
In the visualizer, apply Add a dollar sign and play both versions. In Before, the natural edit is the private helper money(), which print() and save() share, so the step that writes db.rows shows $12.50 landing in accounting's data. With SRP, the edit is in InvoicePrinter and the saved row stays 12.50. Both versions edit exactly one existing class (the panel shows 1 and 1); the difference is what else lives in that class, and therefore what the edit can break.
O: open/closed
Bertrand Meyer stated it in Object-Oriented Software Construction (1988): software entities should be open for extension, but closed for modification. Open means you can add behavior; closed means the existing, tested code that others depend on does not have to be edited to do it. Two readings of how have been taught since:
Meyer's open/closed (1988)
- A finished class is closed: it compiles, ships and is used
- It is extended by inheritance: a subclass adds or overrides behavior
- The original class's code and its clients stay untouched
- Today it survives mainly as Template Method and framework base classes
Polymorphic open/closed (Martin, 1990s)
- Clients depend on an abstract interface, not on implementations
- A new variant is a new class that implements the interface
- The interface and every client stay closed
- The form most people mean today; it relies on LSP and DIP
In the visualizer, the Before rules are plain data with a kind tag, and Pricing.price() switches on it. Notice that no message reaches any rule object: all the logic sits in one method. With OCP, Pricing loops and calls apply() on each rule, and the Rule interface lights up as the type that declares it. Apply Add a coupon: the switch version edits Rule (a min field the other kinds ignore) and Pricing (a new case), 2 existing classes; the OCP version adds Coupon and edits none. Both add the new rule to the client's list.
L: Liskov substitution
Barbara Liskov introduced the idea in her 1987 keynote Data Abstraction and Hierarchy, and with Jeannette Wing gave it a precise form in A Behavioral Notion of Subtyping (1994). Informally: code written against a base type must keep working, without knowing it, when it is handed any subtype. That is a promise about behavior. The type checker only verifies signatures, so a subtype can compile everywhere and still break its callers.
| Rule | What it means | Example violation |
|---|---|---|
| Preconditions cannot be strengthened | Accept every input the base accepts | An overriding withdraw() that rejects amounts the base allows |
| Postconditions cannot be weakened | Guarantee at least what the base guarantees | Square.setWidth() no longer guarantees that the height is unchanged |
| Invariants must be preserved | What is always true of the base stays true | A subclass lets balance go negative when the base forbids it |
| History constraint | Allow no state changes the base type rules out | A mutable subclass of an immutable Point |
| Signature rules | Parameter types may widen, return types may narrow, no new kinds of exceptions | An override that throws UnsupportedOperationException |
In the visualizer, Layout.fit(r: Rectangle) sets width 5, then height 4, and checks that the area is 20. The real Rectangle returns 20. Then the same method gets sq, which the type checker accepts because Square extends Rectangle. Square's setWidth(5) also sets the height (5 by 5), its setHeight(4) also sets the width (4 by 4), the inherited area() returns 16, and fit throws Error: area 16. Layout is correct; the subtype broke a postcondition of its base. With LSP, Square and Rectangle both implement Shape, fit(sq) no longer compiles, and total([rect, sq]) returns 29 with no failure.
I: interface segregation
Martin's statement is clients should not be forced to depend upon interfaces that they do not use. He described it from consulting work at Xerox, where one large Job class served every kind of job in a printer system, so each part of the system depended on methods meant for the others. The harm runs both ways. Implementers must write methods they cannot support, usually a stub that throws. Callers depend on a wider surface than they use, so a change to an unrelated method still reaches them (a rebuild, a retest, a test double that must fake everything).
The Java standard library shows the trade-off in real code: List declares add and remove as optional operations, and the lists returned by List.of(...) or Collections.unmodifiableList(...) throw UnsupportedOperationException when you call them. The JDK chose fewer interfaces over segregation, and every caller holding a List has to know which kind it got. A fat interface with throwing stubs is also an LSP violation, which is why the two principles often appear together.
In the visualizer, Before has one interface, Machine, with print() and scan(). Inkjet can only print, so its scan() throws, and the client's ink.scan("id") compiles because ink is a Machine: the run catches Error: cannot scan. With ISP, Printer and Scanner are separate roles; AllInOne implements both and Inkjet only Printer, so the same call is a compile error. Apply Add scanPdf(): the fat version edits Machine, AllInOne and Inkjet (a second stub), 3 classes; the role version edits Scanner and AllInOne, 2 classes, and never opens Inkjet.
D: dependency inversion
- 1High-level modules should not depend on low-level modules. Both should depend on abstractions.
- 2Abstractions should not depend on details. Details should depend on abstractions.
High-level means policy: the code that says what the application does (place an order). Low-level means mechanism: a database driver, an HTTP client, the file system. In naive layering the policy calls the mechanism directly, so source-code dependencies point the same way as the calls, downward. DIP reverses the source-code arrow, not the call. The interface is declared by and for the high-level module (OrderStore has exactly the method OrderService needs), and the low-level class implements it. At runtime the service still calls the database; at compile time the database class now depends on the policy's interface. That change of ownership is the inversion.
In the visualizer, Before OrderService creates its own MySqlStore, and the class diagram's arrow runs from the service down to the concrete store. With DIP, the service's only arrow points at OrderStore, MySqlStore's arrow points up at that same interface, and the client creates the store and passes it in. Apply In-memory store: before DIP, OrderService itself is edited (a test flag and a second concrete type, 8 changed lines) and gains a second arrow to a concrete class; with DIP, MemoryStore is added, one client line changes, and OrderService is not opened.
- Dependency inversion principle
- A design rule about the direction of source-code dependencies: policy and details both depend on an abstraction that the policy owns.
- Dependency injection
- A technique: an object receives its collaborators (through the constructor, a setter or a parameter) instead of creating them. The usual way to apply DIP; see Dependency Injection.
- Inversion of control
- The broader idea that a framework calls your code instead of your code calling it: callbacks, template methods, event handlers, DI containers.
- DI container
- A library that builds and wires objects from configuration. Optional: passing objects by hand, as the visualizer's client does, is dependency injection too.
SOLID together
The principles reinforce each other. SRP and ISP keep classes and interfaces small and focused. DIP makes the high-level code depend on those interfaces instead of on implementations. LSP makes every implementation safe to plug in. Open/closed is the result: new behavior arrives as new classes behind an abstraction. Remove LSP and the chain breaks, because the "closed" code fails on the first subtype that does not keep its promises. Many patterns are these principles packaged:
| Pattern | Principles | How |
|---|---|---|
| Strategy | OCP, DIP | The context depends on a strategy interface; a new algorithm is a new class |
| Observer | OCP, DIP | The subject depends on a listener interface; new listeners need no change to the subject |
| Template Method | OCP (Meyer's form) | The base class fixes the algorithm; subclasses extend individual steps |
| Decorator | OCP, SRP | Behavior is added by wrapping, one concern per wrapper |
| Adapter | DIP, ISP | A third-party class is fitted to the narrow interface your code owns |
| Dependency Injection | DIP | Implementations are supplied from outside, at the composition root |
Common misreadings
| Misreading | What the principle actually says |
|---|---|
| SRP means a class does one thing, or has one method | One reason to change, meaning one actor. Ten methods that all serve the same actor belong together. |
| OCP means never edit existing code | Fix bugs and refactor freely. The goal is that new variants of an anticipated kind are added, not edited in. |
| LSP is satisfied if the subclass compiles where the parent is expected | The compiler checks signatures. LSP is about behavior: contracts the compiler cannot see. |
| ISP means every interface should have one method | Split by the roles clients actually play; methods used together stay together. |
| DIP is the same as dependency injection | DI is a technique for supplying objects. DIP is about who owns the abstraction and which way the arrows point. Injecting a concrete class is DI without DIP. |
| More classes and interfaces means more SOLID | Each principle buys flexibility along one axis at the cost of indirection. Pay it where change actually happens. |
Summary
| Principle | Question to ask | Fix | What the visualizer shows |
|---|---|---|---|
| SRP | Who asks for changes to this class? | Split by actor | A print-format change leaks into saved rows Before |
| OCP | Does a new variant mean editing a switch? | Polymorphism behind an interface | New coupon: 2 classes edited Before, 0 with OCP |
| LSP | Can every subtype stand in for its base? | Honor the base contract, or do not inherit | fit(sq) throws area 16; with LSP it does not compile |
| ISP | Does any implementer stub a method? | Role interfaces | New scanPdf(): 3 classes edited Before, 2 with ISP |
| DIP | Does the policy name a concrete detail? | Policy-owned interface, injected implementation | The arrows flip; an in-memory store edits OrderService Before, nothing with DIP |
Implementation
The With LSP version of the visualizer as a complete program. Rectangle and Square both implement Shape, whose only promise is area(), and each keeps it. Layout.fit() needs independent width and height, so it takes a Rectangle; passing a Square is rejected by the compiler (or, in Python, by a type checker such as mypy) instead of failing at runtime. Layout.total() needs only areas, so it accepts any Shape.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> int: ...
class Rectangle(Shape):
"""Width and height change independently: fit() relies on that."""
def __init__(self, width: int, height: int) -> None:
self._width = width
self._height = height
def set_width(self, width: int) -> None:
self._width = width
def set_height(self, height: int) -> None:
self._height = height
def area(self) -> int:
return self._width * self._height
class Square(Shape):
"""Not a Rectangle: no setters that break a rectangle's rules."""
def __init__(self, side: int) -> None:
self._side = side
def set_side(self, side: int) -> None:
self._side = side
def area(self) -> int:
return self._side * self._side
class Layout:
def fit(self, r: Rectangle) -> int:
"""Needs a real Rectangle: it sets each side separately."""
r.set_width(5)
r.set_height(4)
a = r.area()
if a != 20:
raise ValueError(f"expected 20, got {a}")
return a
def total(self, shapes: list[Shape]) -> int:
"""Relies only on Shape's contract: any Shape can stand in."""
return sum(s.area() for s in shapes)
rect = Rectangle(2, 3)
sq = Square(3)
layout = Layout()
print(layout.fit(rect)) # 20
# layout.fit(sq) # mypy rejects this: a Square is not a Rectangle
print(layout.total([rect, sq])) # 29Key takeaways
- SOLID is five principles about dependencies, written about by Robert C. Martin and named by Michael Feathers. Their shared goal is code where a change is cheap and stays local.
- SRP: a module should have one reason to change, meaning one actor who requests changes. In the visualizer, a shared helper let a customer-facing format change leak into accounting's saved rows.
- OCP: anticipated new variants should arrive as new classes behind an abstraction, not as edits to a
switch. Adding a coupon edits 2 existing classes in theswitchversion and none with OCP. - LSP: a subtype must keep its base type's contract (preconditions not strengthened, postconditions not weakened, invariants kept).
Square extends Rectanglecompiles and still fails its caller at runtime. - ISP: split fat interfaces into role interfaces, so no class stubs methods it cannot support and no client depends on methods it does not call.
- DIP: the high-level policy owns the interface, the low-level detail implements it, and the client injects it, so the class diagram's arrows point at the abstraction. Dependency injection is the technique; DIP is the principle.
Common pitfalls
- Reading SRP as "one method per class" and splitting a cohesive class into many tiny ones, so every simple change touches several files.
- Adding interfaces, factories and plugin points for variation that never arrives. Each abstraction is a cost; add it when a real second variant or a test double needs it.
- Inheriting to reuse code when the subtype cannot keep the parent's promises, then patching callers with
instanceofchecks or catching "not supported" exceptions. - Calling
newon a database, HTTP client or clock inside business logic, then testing it through global mocks or a real database because nothing can be passed in. - Treating a DI container as DIP. Injecting a concrete class, or an interface that the low-level library owns, keeps the high-level code coupled to the detail.
Interview tips
- For each principle, be ready with four things: the statement, the smell, the fix and the trade-off. "One reason to change, meaning one actor" for SRP and the two parts of DIP are worth memorizing word for word.
- In LLD rounds, apply the principles out loud instead of reciting them: "
ParkingLotdepends on aPricingPolicyinterface, so a new pricing rule is a new class (OCP, DIP)." - Have Rectangle and Square ready, and explain the failure through contracts:
setWidthpromises to leave the height alone, and the override breaks that postcondition. Then offer the fix: separate types behind a common interface, or immutable shapes. - Expect "what is the difference between dependency inversion, dependency injection and inversion of control?" Answer: a principle about who owns the abstraction, a technique for supplying objects, and the broader idea of a framework calling your code.
Real-world applications
- Clean and hexagonal architectures (Layered, Hexagonal & Clean Architecture): the domain declares ports (interfaces) and the infrastructure provides adapters that implement them, which is DIP applied to a whole application.
- Unit testing: services that receive their repositories, clocks and HTTP clients can be tested with in-memory fakes instead of real infrastructure.
- Plugin systems such as IDE extensions, payment gateways and export formats: the host defines an interface and new plugins are new classes (OCP).
- Collection libraries: read-only views versus mutable collections, and the optional operations in Java's
List, are everyday examples of the ISP and LSP trade-off. - Code review: "who else edits this class?" (SRP), "what happens when a new type arrives?" (OCP) and "does this override still honor the parent's contract?" (LSP) are standard review questions.
Test yourself
Which statement matches the single responsibility principle as Robert C. Martin refined it?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.