Skip to the content

Lesson 267 of 296

SOLID principles

What you will learn

  • The five SOLID principles in plain words
  • A TypeScript example of each
  • What each one prevents
  • When applying them is overkill
On this page

SOLID is five object-oriented design principles (named by Robert C. Martin). They help code stay flexible as requirements change. Interviewers often ask you to name and explain them with examples.

S: Single Responsibility Principle

A module or class should have one reason to change: it should serve one part of the business.

Bad: one InvoiceService that calculates totals, renders PDFs, sends emails and writes to the database. A change to the email template and a change to VAT rules both edit the same class.

Good: InvoiceCalculator, InvoicePdfRenderer, InvoiceMailer, InvoiceRepository, coordinated by a small InvoiceService. Each can change and be tested on its own.

O: Open/Closed Principle

Open for extension, closed for modification: add new behaviour by adding new code, not by editing working code.

Bad: a growing switch:

function shippingCost(method: string, weightKg: number) {
  switch (method) {
    case "standard": return 399;
    case "express": return 799 + weightKg * 50;
    // every new method means editing this function
  }
}

Good: each method is its own object implementing an interface; adding "next day" means adding a class, not editing the others. (This is the Strategy pattern, Lesson 269.)

L: Liskov Substitution Principle

A subtype must be usable anywhere its parent type is expected without breaking things. If code works with a Bird, it must work with every kind of bird.

The classic violation:

class Rectangle { setWidth(w) {...} setHeight(h) {...} area() {...} }
class Square extends Rectangle { setWidth(w) { width = height = w } ... }

Code that sets width 5 and height 4 expects area 20, but a Square returns 16. The subclass changed the parent's promised behaviour. Symptoms of LSP violations: subclasses that throw "not supported" for inherited methods, or callers checking instanceof to treat a subtype specially. Fixes: do not force the inheritance; use separate types or composition (Lesson 268).

I: Interface Segregation Principle

Do not force clients to depend on methods they do not use. Prefer several small, focused interfaces over one large one.

TypeScript
interface Readable<T> {
  findById(id: string): Promise<T | null>;
}

interface Writable<T> {
  save(entity: T): Promise<void>;
}

type Report = { id: string; title: string };

export class ReportViewer {
  constructor(private readonly reports: Readable<Report>) {}

  async title(id: string): Promise<string> {
    return (await this.reports.findById(id))?.title ?? "Not found";
  }
}

ReportViewer only needs to read, so it depends on Readable alone. Its test fake implements one method, and a read-only replica repository can be passed in. (Writable is shown for the contrast: a class that saves reports would depend on that.)

D: Dependency Inversion Principle

High-level business logic should not depend on low-level details; both should depend on abstractions.

TypeScript
export interface PaymentGateway {
  charge(customerId: string, amountPence: number): Promise<{ ok: boolean; reference: string }>;
}

export class CheckoutService {
  constructor(private readonly payments: PaymentGateway) {}

  async checkout(customerId: string, amountPence: number): Promise<string> {
    if (amountPence <= 0) throw new Error("Amount must be positive");
    const result = await this.payments.charge(customerId, amountPence);
    if (!result.ok) throw new Error("Payment declined");
    return result.reference;
  }
}

CheckoutService (the business rule) knows nothing about Stripe. A StripeGateway and a test FakeGateway both implement PaymentGateway. Switching providers or testing needs no change to the business logic. Dependency injection (Lesson 208) is the technique that delivers the abstraction at runtime.

When SOLID is overkill

SOLID is guidance, not law. Creating interfaces for every class "in case" adds files and indirection with no benefit. Apply the principles where change is likely or already happening, where testing needs a seam, or where a class has become hard to understand. A small script or a simple CRUD endpoint does not need five layers.

How to say it in an interview

"SOLID is five design principles. Single responsibility: one reason to change, so I separate calculation, rendering, sending and persistence. Open/closed: extend by adding code, for example new strategies, instead of editing a growing switch. Liskov substitution: subtypes must keep the parent's promises, which the square-rectangle example breaks. Interface segregation: small focused interfaces so clients depend only on what they use. Dependency inversion: business logic depends on abstractions like a PaymentGateway interface, with concrete implementations injected, which makes testing and swapping easy. I apply them where change or testing needs them, not everywhere by default."

Key words

WordMeaning
SOLIDFive object-oriented design principles
Single responsibilityOne reason to change
Open/closedExtend without modifying existing code
Liskov substitutionSubtypes must work wherever the parent works
Interface segregationSmall, client-specific interfaces
Dependency inversionDepend on abstractions, not concrete details

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.