smaple.tr
Backend & APIs

SOLID Principles: Five Rules, One Real Problem, and When to Skip Them

Mehmet Kurtipek
February 20, 2026
16 min read
Backend & APIs
SOLID
TypeScript
Software design
Refactoring

SOLID is a set of five design principles for object-oriented code: Single responsibility, Open/closed, Liskov substitution, Interface segregation and Dependency inversion. Each one targets a different way code becomes hard to change, and together they aim at one result: you can change one part of a system without breaking parts that have nothing to do with it. Treat them as questions to ask while designing. Applied everywhere by reflex, they produce the over-abstracted code they were meant to prevent.

The five principles at a glance

Principle

The rule in one line

Symptom when it's broken

Single responsibility (SRP)

A module has one reason to change: one group of people asking for changes

A change for one team breaks a feature another team relies on

Open/closed (OCP)

New behavior arrives as new code; tested code stays as it is

Every new variant adds another branch to the same switch

Liskov substitution (LSP)

Every implementation of an interface honors that interface's contract

Callers check which concrete class they got, or wrap one of them in special-case try blocks

Interface segregation (ISP)

Clients don't depend on methods they don't use

Classes full of methods that throw "not supported"

Dependency inversion (DIP)

Business rules depend on abstractions they own; databases and vendors plug into them

You can't test a rule without a database, an HTTP server or an API key

The example we'll use

Most SOLID tutorials reuse the same three examples: a Square that extends Rectangle, a Worker interface with an eat() method, and a UserService that does everything. We'll use one problem throughout instead. It comes from our work for Oplist, a client with a shift-scheduling SaaS for hospitals. We have been Oplist's engineering team since November 2023.

A rostering system has to know who is away. Oplist receives leave records from private hospitals' HR and payroll systems over live API integrations: sick leave and other leave reasons, hourly leaves, and block leaves such as training. Two details make this harder than it sounds. The hospitals' source systems can contain duplicate staff records, and some leave types take precedence over others, so we deduplicate and apply a precedence order inside Oplist instead of trusting the source. And the rostering rules depend on the leave type: an hourly leave doesn't take someone out of the whole day, a training block does. "Unavailable" isn't enough information.

The code below is a simplified version written for this post, in TypeScript. Blocks marked as sketches leave out the plumbing; the rest type-check with strict on. None of it is Oplist's code.

Single responsibility: one reason to change

Robert C. Martin's definition is easy to misread as "a class should do one thing". In his 2014 clarification he says the principle is about people: a module should answer to one group of stakeholders, so that a change requested by one group can't break something another group depends on.

Here is a leave importer that answers to three groups at once:

// Sketch: one class, three reasons to change
class LeaveImporter {
  async run(hospitalId: string, from: Date, to: Date): Promise<void> {
    const rows = await this.hrClient.get(`/leaves?from=${iso(from)}&to=${iso(to)}`); // the HR vendor's format
    const leaves = rows.map(toLeave);
    const resolved = dedupeAndApplyPrecedence(leaves);                       // rostering rules
    await this.db.leaves.upsertMany(hospitalId, resolved);                   // storage
    await this.mailer.send(this.managerOf(hospitalId), summarize(resolved)); // notifications
  }
}

The HR vendor changes its API: someone edits run. The hospital decides training should outrank annual leave: someone edits run. Operations wants the daily summary in Slack instead of email: run again. Each edit puts the other two at risk, and testing the precedence rule means mocking an HTTP client, a database and a mailer.

Split it along those lines:

// Sketch
interface LeaveSource {
  fetchLeaves(from: Date, to: Date): Promise<Leave[]>; // talks to one HR system
}

// Pure: deduplicate, then keep the stronger leave per person per day (body in the next section)
function resolveLeaves(raw: Leave[]): Leave[];

async function importLeaves(source: LeaveSource, store: LeaveStore, notify: Notify, from: Date, to: Date) {
  const leaves = resolveLeaves(await source.fetchLeaves(from, to));
  await store.save(leaves);
  await notify(summarize(leaves));
}

The most valuable piece is resolveLeaves. It takes an array and returns an array, so the rules that matter most (which record is a duplicate, which leave wins) can be tested with plain data and no mocks. Rules like these also outlive the stack around them. When a UI and an API move to a new framework, the rule module should come across unchanged, together with its tests.

When to skip it: a 40-line script that runs once, or a class where every change request comes from the same person. Splitting those adds files and jumps without separating anything that changes independently. A quick test is to write down who would ask for each kind of change to the module. If you get one name or one team, leave it alone.

Open/closed: add behavior without editing what works

Bertrand Meyer coined the open/closed principle in 1988, in a form based on inheritance. The version most people use today, which Martin popularized in the 1990s, says that when a new variant arrives you should be able to add it without editing code that already works and is tested.

Leave precedence is a good candidate, because new leave types can appear: a hospital adds a training category, or a new leave reason starts coming through the integration. The usual first version is a chain of if statements inside the resolver. In TypeScript the cleaner move is often a data table, with the type system making sure nobody forgets a row:

type LeaveType = "sick" | "annual" | "hourly" | "training";

interface Leave {
  id: string;
  staffId: string;
  type: LeaveType;
  start: Date;
  end: Date;
}

// The order is made up for this example. In practice it comes from the hospital's rules.
const leavePolicies: Record<LeaveType, { precedence: number; blocksWholeDay: boolean }> = {
  sick:     { precedence: 40, blocksWholeDay: true },
  training: { precedence: 30, blocksWholeDay: true },
  annual:   { precedence: 20, blocksWholeDay: true },
  hourly:   { precedence: 10, blocksWholeDay: false },
};

function stronger(a: Leave, b: Leave): Leave {
  return leavePolicies[a.type].precedence >= leavePolicies[b.type].precedence ? a : b;
}

// Simplified: one key per person per start day
function resolveLeaves(raw: Leave[]): Leave[] {
  const unique = new Map(raw.map((l) => [l.id, l] as const)); // same record fetched twice
  const perStaffDay = new Map<string, Leave>();
  for (const leave of unique.values()) {
    const key = `${leave.staffId}:${leave.start.toISOString().slice(0, 10)}`;
    const current = perStaffDay.get(key);
    perStaffDay.set(key, current ? stronger(current, leave) : leave);
  }
  return [...perStaffDay.values()];
}

Adding a "conference" leave type now means one new member in the union and one new row in the table. Record<LeaveType, ...> stops the table from compiling until the row exists, and resolveLeaves doesn't change. (Deduplicating staff records belongs in the same module; it's left out to keep the example short.)

When to skip it: the first time. One if is fine, and a strategy interface with a single implementation is a guess about the future. We'd wait until the second or third variant shows up and the edits start to hurt. There is also a case where a plain switch is the better design: the set of variants is fixed, but you keep adding operations over it (labels, roster colors, payroll codes). An exhaustive switch makes the compiler point at every place that needs updating:

function label(type: LeaveType): string {
  switch (type) {
    case "sick": return "Sick leave";
    case "annual": return "Annual leave";
    case "hourly": return "Hourly leave";
    case "training": return "Training";
    default: {
      const unhandled: never = type; // compile error here when a new LeaveType is added
      throw new Error(`Unhandled leave type: ${unhandled}`);
    }
  }
}

Liskov substitution: honor the contract

Barbara Liskov described the idea in a 1987 keynote, and she and Jeannette Wing formalized it in their 1994 paper A Behavioral Notion of Subtyping. In practical terms, an implementation of an interface:

  • may not demand more from callers than the interface does (no stronger preconditions),
  • may not promise less than the interface does (no weaker postconditions),
  • must keep the interface's invariants, and must not allow state changes the base type rules out.

The first two are easy to get backwards. An implementation may accept more than the interface requires and promise more than it guarantees. The violations go the other way.

Write the contract down where callers can see it:

interface LeaveSource {
  /** Every leave overlapping [from, to], for a range of any length, each with its real type. */
  fetchLeaves(from: Date, to: Date): Promise<Leave[]>;
}

Now suppose one vendor's API accepts at most 31 days per request. The tempting adapter throws when the range is longer. That is a stronger precondition: the roster generator asks for a quarter, and code that works with every other source fails with this one. Absorb the limit inside the adapter:

const DAY = 24 * 60 * 60 * 1000;

function* windows(from: Date, to: Date, maxDays: number): Generator<[Date, Date]> {
  for (let start = from.getTime(); start < to.getTime(); start += maxDays * DAY) {
    yield [new Date(start), new Date(Math.min(start + maxDays * DAY, to.getTime()))];
  }
}

class VendorLeaveSource implements LeaveSource {
  constructor(private readonly fetchPage: (from: Date, to: Date) => Promise<Leave[]>) {}

  async fetchLeaves(from: Date, to: Date): Promise<Leave[]> {
    const leaves: Leave[] = [];
    for (const [start, end] of windows(from, to, 31)) {
      leaves.push(...(await this.fetchPage(start, end))); // vendor limit: 31 days per call
    }
    return leaves; // a leave spanning two windows comes back twice; resolveLeaves drops the copy
  }
}

A postcondition can break just as quietly. An adapter that maps leave codes it doesn't recognize to "annual" still returns a well-typed Leave[], but it promises less than the interface: the type is no longer the real type, and the roster treats an hourly leave as a full day off. Reject unknown codes, or flag them for a person to review. Don't guess.

The same rule is what makes fallbacks safe. On the real-time odds data platform we built and ran for EdgeHunters over about two and a half years, each sportsbook had its own scraper, and a third-party odds API took over automatically when a scraper failed. A fallback like that is only safe when the code downstream can't tell which source the data came from: same shape, same normalized names.

Two notes on what compilers will and won't catch. TypeScript checks method parameters bivariantly, even with strict on (the default since TypeScript 6.0), so an implementation can quietly narrow what it accepts:

type Recipient = { email: string } | { phone: string };

interface Notifier {
  send(to: Recipient, text: string): Promise<void>;
}

class SmsNotifier implements Notifier {
  // Compiles with "strict": true. A caller holding a Notifier can still pass { email },
  // and this line then crashes at runtime.
  async send(to: { phone: string }, text: string): Promise<void> {
    console.log(`SMS to ${to.phone.trim()}: ${text}`);
  }
}

Declare the member as a property (send: (to: Recipient, text: string) => Promise<void>) and strictFunctionTypes applies: the narrower implementation is rejected. In Java and C#, a method with a narrower parameter type is an overload, so the class doesn't compile as an implementation in the first place. There, substitution problems show up at runtime, usually as a method that throws. The JDK does this on purpose: List documents add as an "optional operation", and a list from List.of throws UnsupportedOperationException when you call it. That's within the documented contract, and it's also why code that receives a List can't safely call add without knowing where the list came from.

Interface segregation: a small interface per client

Clients shouldn't depend on methods they don't use. Picture a single interface for everything a hospital system can do:

type Staff = { id: string; name: string };                        // trimmed
type HoursRow = { staffId: string; date: string; hours: number }; // trimmed

interface HrSystem {
  fetchStaff(): Promise<Staff[]>;
  fetchLeaves(from: Date, to: Date): Promise<Leave[]>;
  pushWorkedHours(rows: HoursRow[]): Promise<void>; // used only by the payroll export
}

The roster generator needs staff and leaves. Only the payroll export pushes hours. With one interface, an integration for a system that can't accept hours still has to implement pushWorkedHours, usually as a method that throws, which is the substitution problem from the previous section. And every test fake has to stub three methods to exercise one.

Split it by client:

interface StaffDirectory { fetchStaff(): Promise<Staff[]> }
interface LeaveSource { fetchLeaves(from: Date, to: Date): Promise<Leave[]> }
interface HoursSink { pushWorkedHours(rows: HoursRow[]): Promise<void> }

async function buildRosterInput(hr: StaffDirectory & LeaveSource, from: Date, to: Date) {
  const [staff, leaves] = await Promise.all([hr.fetchStaff(), hr.fetchLeaves(from, to)]);
  return { staff, leaves: resolveLeaves(leaves) };
}

One adapter class can still implement all three. Structural typing makes this cheap in TypeScript: a function asks for exactly the members it uses (an intersection like the one above, or Pick<HrSystem, "fetchLeaves">), and any object with those members fits, including a two-line test fake.

The same thinking applies to HTTP APIs. An endpoint that returns 40 fields because one screen needed all of them makes every other consumer depend on all 40.

When to skip it: one client and one implementation. Splitting an interface nobody else uses is busywork.

Dependency inversion: business rules own the interfaces

High-level policy shouldn't depend on low-level details. Both should depend on abstractions, and the abstraction belongs to the policy side. In the leave example, the import code defines LeaveSource and each hospital's adapter implements it, so the vendor's client library is imported in exactly one file.

Dependency injection is the usual way to wire this up: pass the implementation in through a constructor or a parameter. A DI container is optional; a few lines of startup code do the same job.

The payoff comes when a dependency misbehaves. The field-ticket automation we built with an agency partner for an oilfield services company reads about 100 documents a day with an LLM. What broke in production was mostly rate limiting on the LLM API (HTTP 429), and the fix was falling back to alternative models. That project is an n8n workflow, so the fallback is a branch in the workflow. In application code the same change stays small when the job depends on an interface it owns:

interface FieldTicket { ticketNumber: string; customer: string; hours: number } // trimmed

interface Extractor {
  extract(pdf: Uint8Array): Promise<FieldTicket>;
}

class RateLimitError extends Error {}

class FallbackExtractor implements Extractor {
  constructor(private readonly chain: Extractor[]) {}

  async extract(pdf: Uint8Array): Promise<FieldTicket> {
    let lastError: unknown = new Error("No extractors configured");
    for (const extractor of this.chain) {
      try {
        return await extractor.extract(pdf);
      } catch (err) {
        if (!(err instanceof RateLimitError)) throw err; // don't hide real bugs behind a retry
        lastError = err;
      }
    }
    throw lastError;
  }
}

// Startup code is the only place that knows the concrete models:
// const extractor = new FallbackExtractor([primaryModel, secondaryModel]);

The ticket job never learns that a fallback exists. FallbackExtractor is itself an Extractor, so this one small class also shows open/closed (new behavior, no edits to the job) and substitution (it keeps the same contract).

Where SOLID goes too far

Each principle has a failure mode when it's applied by reflex:

  • An interface for every class, each with exactly one implementation forever (IUserService next to UserServiceImpl). That's an extra file and an extra jump in the editor for nothing. Keep interfaces for real boundaries: I/O, vendors, the clock, anything you need to fake in a test.
  • Responsibilities split so finely that one feature touches nine files. Martin's own summary of SRP works in both directions: gather together the things that change for the same reasons. If two classes always change together, they probably belong together.
  • Extension points for variants nobody has asked for. Each one is more code to read, test and keep compatible.

Not everyone thinks SOLID is still the right frame. Dan North, who created behavior-driven development, wrote in 2022 that he no longer finds the principles useful and proposed CUPID instead: a set of properties of good code (composable, Unix philosophy, predictable, idiomatic, domain-based) in place of rules. His argument that splitting by SRP can create artificial seams is worth keeping in mind.

Our view: SRP and DIP pay for themselves on almost any codebase that will live for years, mostly because they make the important logic testable. LSP is a correctness rule; break it and you get bugs, whatever your style. OCP and ISP are the ones to apply late, once the second variant or the second client actually exists.

Applying SOLID to code you already have

Don't refactor a whole codebase toward SOLID. Start where change hurts.

  1. Find the hotspots. The files that change most often are where poor structure costs you most:
git log --since="6 months ago" --name-only --pretty=format: | grep -v '^$' | sort | uniq -c | sort -rn | head -20
  1. Put tests around current behavior before you move anything. If there are none, characterization tests that pin down today's output are enough to start; our post on test-driven development covers the habit.
  2. Pull pure logic out of classes that also do I/O (SRP). It's usually the biggest return for the least risk.
  3. Put an interface you own at each vendor boundary (DIP), so the next API change or outage is a change in one adapter.
  4. Split a fat interface when writing a test fake for it gets annoying (ISP), and replace a growing switch once it changes every sprint (OCP).

If every change in your codebase breaks something unrelated, that's the kind of work we take on under maintenance and support; for bigger rewrites, see our notes on legacy system modernization.

Frequently asked questions

Who created the SOLID principles?

Robert C. Martin assembled the set and wrote most of it up in his 2000 paper Design Principles and Design Patterns. Two of the ideas are older: open/closed comes from Bertrand Meyer and substitution from Barbara Liskov. By Martin's account, Michael Feathers emailed him around 2004 to point out that the initials, reordered, spell SOLID.

Are the SOLID principles still relevant?

For object-oriented and TypeScript code that will be maintained for years, yes, as long as you use them to ask questions about a design instead of as a checklist. They matter less in small scripts, and less in code where the main structure comes from a framework you don't control.

Do SOLID principles apply outside object-oriented code?

The ideas do, under other names. Go interfaces are satisfied implicitly and Python has duck typing and typing.Protocol, which makes interface segregation and dependency inversion cheap in both. In functional code, passing a function as an argument is dependency inversion, and a small pure function with one reason to change is single responsibility.

How should I explain SOLID in an interview?

Name the five, then give one example per principle from code you've worked on, and say when you'd skip it. State the substitution rule precisely: no stronger preconditions, no weaker postconditions. An example from your own work will stand out more than Square and Rectangle.

Related Articles

August 1, 2026

Kong vs Traefik vs AWS API Gateway: How to Choose

Kong, Traefik and AWS API Gateway compared as of October 2026: features, licensing, Kubernetes support and what AWS charges for 100 million requests a month.

Read More: Kong vs Traefik vs AWS API Gateway: How to Choose
July 4, 2026

gRPC vs REST for Microservices: When gRPC Is Worth It

When gRPC beats REST between services, what it adds to your operations (load balancing, deadlines, browser access), and what our own protobuf vs JSON test showed.

Read More: gRPC vs REST for Microservices: When gRPC Is Worth It
March 14, 2026

RPA Implementation: From Process Choice to Bots That Keep Running

Most of an RPA implementation is choosing the process and designing for exceptions. The order we work in, current license prices, and what broke in the n8n and LLM automation we built with an agency.

Read More: RPA Implementation: From Process Choice to Bots That Keep Running