SOLID principles interview questions with code examples
SOLID principles interview questions ask you to explain the five object-oriented design principles (single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion), spot a violation in a piece of code, and refactor it without overbuilding. Junior rounds want a correct definition with one example per letter; experienced rounds want the reasoning behind each principle, the trade-offs, and the judgment to say when applying it would add complexity for nothing. The best answers show code before and after.
By Evin JohnPublished 9 min read
How SOLID shows up in interviews
SOLID questions come in three shapes. The quick version is "explain SOLID", common in screening calls and fundamentals rounds for Java, C#, C++, Python and TypeScript roles. The practical version hands you a class (often an OrderService or ReportGenerator that does everything) and asks what is wrong with it. The senior version asks for opinions: which principle matters most, when SOLID hurts, and how it applies to code that is not object-oriented at all. Prepare all three, because interviewers move from the first to the third in a single conversation.
Fundamentals
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does SOLID stand for? | Recall | Single responsibility, open/closed, Liskov substitution, interface segregation, dependency inversion. Credit the principles to Robert C. Martin's writing; the acronym itself is usually attributed to Michael Feathers. |
| Why do these principles exist at all? | Purpose | To keep code cheap to change. Each one limits how far a change ripples: fewer reasons to edit a class, fewer callers broken by a new subtype, fewer modules recompiled or retested because of a detail. |
| Define the single responsibility principle precisely. | Precision | A module should have one reason to change. "Does one thing" is the popular reading, but Martin later framed it as being responsible to one actor, the group of people who would request its changes. |
| What does "open for extension, closed for modification" mean in practice? | Interpretation | You add a new case by writing a new class or registering a new function, while existing code that is tested and shipped stays untouched. |
| State the Liskov substitution principle without jargon. | Understanding | Anywhere the program uses a base type, any subtype must work without the caller noticing or needing special checks. |
| What is interface segregation? | Coupling | Clients should not depend on methods they do not use. Split a broad interface into smaller role interfaces so a change for one client does not touch the others. |
| What is dependency inversion? | Architecture | High-level policy should not depend on low-level details; both should depend on abstractions, and the abstraction belongs with the policy that needs it. |
| How do cohesion and coupling relate to SOLID? | Big picture | SRP and ISP raise cohesion; OCP, LSP and DIP lower coupling or make it safe. Together they aim for modules that change for their own reasons only. |
Single responsibility: reasons to change
- How do you find SRP violations in a class? List who would ask for each change. If finance changes tax rules, design changes the layout and operations changes delivery, and all three edit one class, it has three responsibilities.
- Is a class with one public method automatically SRP-compliant? No. A single
process()method can still mix validation, persistence and email. Responsibility is about change pressure, not method count. - Can SRP go too far? Yes. Splitting every function into its own class scatters logic and makes a simple flow hard to follow. Split when changes actually arrive from different directions.
- How does SRP apply above the class level? The same reasoning works for modules and services: a service that two teams keep editing for unrelated reasons is a candidate for splitting.
from dataclasses import dataclass
@dataclass
class Invoice:
customer: str
lines: list # (description, quantity, unit_price)
def invoice_total(inv, tax_rate):
subtotal = sum(q * p for _, q, p in inv.lines)
return round(subtotal * (1 + tax_rate), 2)
def render_text(inv, total):
rows = [d + " x" + str(q) for d, q, _ in inv.lines]
return inv.customer + ": " + ", ".join(rows) + " = " + str(total)
class Outbox: # delivery is swappable: email, file, queue
def __init__(self):
self.sent = []
def send(self, message):
self.sent.append(message)
inv = Invoice("Acme", [("widget", 3, 10.0), ("bolt", 10, 0.5)])
out = Outbox()
out.send(render_text(inv, invoice_total(inv, 0.2)))
print(out.sent) # ['Acme: widget x3, bolt x10 = 42.0']Open/closed: extending without editing
- Show an OCP violation. A function with a switch on a type field (
if shape.kind == "circle" ... elif ...) that must be edited and retested every time a new type arrives, often in several places at once. - How do you fix it? Polymorphism (each type implements the behavior) or a registry that maps a key to a handler. New types then arrive as new code.
- Is it possible to be closed against every change? No. You choose which axis of change to protect against, based on what has actually varied. Guessing wrong adds abstraction in the wrong place.
- How do plugins, middleware and feature flags relate to OCP? All three add behavior at defined extension points without editing the core, which is OCP applied at the system level.
const areaRules = new Map();
const register = (kind, fn) => areaRules.set(kind, fn);
const areaOf = (shape) => {
const rule = areaRules.get(shape.kind);
if (!rule) throw new Error("no area rule for " + shape.kind);
return rule(shape);
};
register("circle", (s) => Math.PI * s.r * s.r);
register("rect", (s) => s.w * s.h);
// Adding a triangle later is one new line, not an edit to areaOf:
register("triangle", (s) => 0.5 * s.base * s.height);
const shapes = [{ kind: "rect", w: 2, h: 3 }, { kind: "triangle", base: 4, height: 5 }];
console.log(shapes.map(areaOf)); // [ 6, 10 ]Liskov substitution: keeping the contract
- What are the contract rules behind LSP? A subtype may not strengthen preconditions (accept less), may not weaken postconditions (promise less), must preserve the parent's invariants, and should not throw new kinds of exceptions callers were never told about.
- Why does the square and rectangle example break LSP? Code written for a rectangle assumes width and height change independently. A square that forces them equal keeps itself valid but breaks that assumption, so a caller that worked with rectangles fails.
- Give an LSP violation from a standard library. Read-only or fixed-size collections that implement a general list interface and throw on
addare a common example, since callers of the interface had no warning. - How do you spot LSP problems in a code review?
instanceofor type checks on a subtype, overridden methods that throw "not supported", and empty overrides that silently do nothing. - How do you fix an LSP violation? Stop inheriting and share an interface that only promises what both types can keep, or use composition. The fix is in the type hierarchy, not in the callers.
class Rectangle:
def __init__(self, w, h):
self.w, self.h = w, h
def set_width(self, w):
self.w = w
def area(self):
return self.w * self.h
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
def set_width(self, w): # keeps the square valid...
self.w = self.h = w # ...but breaks the parent's promise
def stretch(rect):
"""Caller written against Rectangle: widening should not change height."""
before = rect.h
rect.set_width(rect.w * 2)
return rect.h == before
print(stretch(Rectangle(2, 3))) # True
print(stretch(Square(2))) # False: Square is not a safe substituteInterface segregation and dependency inversion
- What does a fat interface cost? Implementers write stub methods they do not need, and clients recompile or retest when an unrelated method changes. A
Printerinterface with scan and fax methods forces a basic printer to fake them. - How small should interfaces be? Shaped by what each client needs, often one to a few methods. A class can implement several role interfaces at once.
- Does ISP matter in duck-typed languages? The compile-time effect is gone, but the design idea remains: a function that only reads should accept something with a read method, not a full storage client. Python protocols and TypeScript structural types express this directly.
- What is the difference between dependency inversion, dependency injection and inversion of control? DIP is the design rule about which way dependencies point. Dependency injection is a technique: passing collaborators in from outside, usually through the constructor. Inversion of control is the broader idea that a framework or container calls your code and wires it.
- Who should own an abstraction under DIP? The high-level module that uses it. If the payment interface is defined by the vendor SDK wrapper, the business logic still depends on the detail; define the interface in the domain and adapt the SDK to it.
- Is a service locator a form of dependency inversion? It inverts creation but hides what a class depends on, since the dependencies are fetched inside instead of declared in the constructor. Most reviewers prefer explicit injection.
- Where should objects be wired together? In one composition root near the program's entry point, or in a DI container configured there, so the rest of the code never calls constructors of its dependencies.
class ReportService {
constructor(source, sink) { // any object with load() / any with write(text)
this.source = source;
this.sink = sink;
}
run() {
const rows = this.source.load();
const total = rows.reduce((sum, r) => sum + r.amount, 0);
this.sink.write("rows=" + rows.length + " total=" + total);
}
}
// A test needs no database and no file system: plain fakes satisfy the contract.
const fakeSource = { load: () => [{ amount: 5 }, { amount: 7 }] };
const written = [];
const fakeSink = { write: (text) => written.push(text) };
new ReportService(fakeSource, fakeSink).run();
console.log(written); // [ 'rows=2 total=12' ]Senior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Which SOLID principle do you think matters most, and why? | Opinion with reasons | Any choice is fine with a reason from experience. Many engineers pick DIP because it makes testing and swapping infrastructure cheap, or SRP because most messy code is mixed responsibilities. |
| When does following SOLID make code worse? | Restraint | An interface for every class with one implementation, factories for objects that never vary, and layers of indirection in a small script. Apply principles where change actually happens. |
| How does SOLID apply to React components or functional code? | Transfer | SRP maps to small components and hooks with one concern, OCP to composition through props and children, and DIP to passing functions or context instead of importing concrete services. |
| Two principles pull in different directions. Example? | Nuance | Splitting for SRP can create many small types that each need an interface for DIP, raising the cost of navigation. Balance against how often each part changes. |
| You inherit a 3,000-line class. Where do you start? | Legacy refactor | Add characterization tests around its current behavior, extract the most frequently changed responsibility first, inject its dependencies, and repeat in small, safe steps. |
| How do you explain SOLID to a junior developer? | Communication | One sentence per principle with a smell to look for: too many reasons to change, a growing switch, a subtype that needs special cases, stub methods, and business code calling new on infrastructure. |
| How do SOLID ideas show up in microservices? | Scale | A service with one business capability is SRP at a larger size; stable, versioned APIs resemble OCP; consumers depending on contracts rather than implementations echoes DIP. |
Fictional example
- Interviewer
- OrderService validates the cart, calculates tax with a switch per country, saves to MySQL through a static helper, and sends a confirmation email. What would you change?
- Candidate
- Three different groups ask for changes here: whoever owns pricing and tax, whoever owns storage and whoever owns customer messaging, so I would separate those first. The tax switch grows with every new country, so I would move each country's rule behind a TaxRule interface and look them up from a registry, which keeps the order flow closed to edits when we expand. The static MySQL helper is the biggest testing problem, so OrderService should take an OrderRepository interface it owns through its constructor, with a MySQL implementation outside the domain. Same for a Notifier. I would not split validation into its own class yet unless the rules are big or shared. Before touching anything, I would write tests around current behavior, then do one extraction at a time so each step is easy to review.
A one-week SOLID practice plan
- Day 1: one sentence and one smell per letterWrite a definition you could say in ten seconds and the code smell that signals a violation.
- Days 2 and 3: before and after codeFor each principle, write a violating snippet and its refactor in your interview language, and run both.
- Day 4: the Liskov rulesPractice the precondition, postcondition and invariant rules on three hierarchies of your own, not only squares and rectangles.
- Day 5: DIP versus DI versus IoCExplain the three aloud until the difference is crisp, then wire a small app through a composition root.
- Days 6 and 7: review real codeTake a messy class from an old project and do a timed review aloud: what you would change first, and what you would leave alone.
SOLID is the reasoning behind most patterns, so continue with design patterns interview questions and the broader OOP interview questions. Language-specific rounds go deeper on the Java developer and TypeScript pages.
Refactoring questions are easiest to judge after the fact, by reading what you said. Natively, an AI interview assistant for Mac and Windows, records a transcript of your mock review, can propose an answer in the moment when you cannot name the principle a snippet breaks, and reads a code sample from a screenshot so you can compare its refactor with yours. With your résumé and the job description added (Pro or the free trial), its suggestions lean on the languages and codebases you list.
Questions people ask
What are the SOLID principles?
Single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion: five object-oriented design principles that aim to keep code easy to change, test and extend.
How do I explain SOLID in an interview?
Give one plain sentence per principle, a short example of a violation, and the refactor that fixes it. For experienced roles, add when you would not apply it.
What is the difference between dependency inversion and dependency injection?
Dependency inversion is a design rule: high-level code and low-level details both depend on abstractions owned by the high-level side. Dependency injection is a technique for supplying those dependencies from outside, usually through the constructor.
Why does a square subclassing a rectangle violate Liskov substitution?
Callers of a rectangle expect width and height to change independently. A square must keep them equal, so code that works with any rectangle gives wrong results with a square.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
