The SOLID Principles Explained with Code Examples

The SOLID principles explained in plain terms: five rules that keep a codebase easy to change long after the first version ships. Each principle fixes a specific kind of pain, the kind you feel when a small change breaks three unrelated features or when a class grows so large nobody wants to touch it. This guide walks through all five with short TypeScript examples you can run and adapt, so you can see each rule in action instead of just reading its definition.

SOLID principles explained in plain terms

SOLID is an acronym for five design rules from Robert C. Martin: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. They are not a framework and they do not require a rewrite. They are checks you apply while writing code, and they pay off most when a project grows past the point where one person holds the whole design in their head. If you are still getting comfortable with functions as values and scope, our guide to JavaScript closures with real code examples is a useful warm-up, since several examples below lean on those ideas.

1. Single Responsibility Principle

A class should have one reason to change. When a class handles two jobs, a change to one job risks breaking the other. Take a class that saves a user and also sends the welcome email:

class UserService {
  save(user) { /* write to database */ }
  sendWelcomeEmail(user) { /* build and send email */ }
}

If the email provider changes, you edit the same class that owns database logic, and a mistake there can break saving users. Split the jobs apart:

class UserRepository {
  save(user) { /* write to database */ }
}

class EmailService {
  sendWelcome(user) { /* build and send email */ }
}

Now each class changes for one reason only. The same idea applies to functions and modules: when a function does three things, pull the parts out until each piece has one clear job. Python decorators show a similar split in another language, wrapping one job around another instead of mixing them.

2. Open/Closed Principle

Code should be open for extension but closed for modification. In practice that means adding a new behaviour without editing the code that already works. A discount calculator that switches on a type string breaks this rule:

function discount(type, price) {
  if (type === "student") return price * 0.8;
  if (type === "member") return price * 0.9;
  return price;
}

Every new discount type means editing this function and retesting every branch. Use a small strategy object instead:

const discounts = {
  student: (price) => price * 0.8,
  member: (price) => price * 0.9,
  none: (price) => price,
};

function discount(type, price) {
  return discounts[type](price);
}

Adding a new discount now means adding one entry, not touching the function. This pattern shows up everywhere, from payment methods to report formats, and it is the reason experienced developers reach for a lookup table before a long if-else chain.

3. Liskov Substitution Principle

A subclass must be usable anywhere its parent class is used, without breaking expectations. The classic violation is a Square that extends Rectangle and then breaks the area math, because setting the width of a square also changes its height:

class Rectangle {
  constructor() { this.width = 0; this.height = 0; }
  area() { return this.width * this.height; }
}

class Square extends Rectangle {
  set width(value) {
    this._width = value;
    this._height = value;
  }
}

Code that sets width to 4 and height to 5 expects an area of 20, but a Square returns 25, so the subclass quietly breaks the parent contract. The fix is to stop forcing the wrong relationship: give Square and Rectangle a shared Shape interface instead of inheriting one from the other, or simply do not subclass when the behaviour does not fit. The rule of thumb is simple: if a subclass needs to change what the parent promises, the inheritance is wrong. This matters most in typed codebases, so if your project is still plain JavaScript, our guide on migrating a JavaScript project to TypeScript will help you catch these mismatches at compile time.

4. Interface Segregation Principle

No client should be forced to depend on methods it does not use. A fat interface pushes every implementer to stub out methods that mean nothing to them:

interface Worker {
  work(): void;
  eat(): void;
  attendMeeting(): void;
}

A robot worker that never eats still has to implement eat, usually as an empty method or one that throws an error. Split the interface into small pieces:

interface Workable { work(): void; }
interface Eatable { eat(): void; }
interface Attendee { attendMeeting(): void; }

Now each class picks only the interfaces it needs. Small interfaces are also easier to test, because a test double only has to fake one behaviour instead of a whole grab bag of methods. If you are weighing how TypeScript fits this style of design, our TypeScript vs JavaScript in 2026 comparison covers when the extra types pay off.

5. Dependency Inversion Principle

High-level code should depend on abstractions, not on concrete details. A notification service that creates its own email sender is stuck with that sender forever:

class Notifier {
  constructor() {
    this.sender = new EmailSender();
  }
  notify(message) {
    this.sender.send(message);
  }
}

To switch to SMS you have to edit the Notifier. Pass the sender in instead:

class Notifier {
  constructor(sender) {
    this.sender = sender;
  }
  notify(message) {
    this.sender.send(message);
  }
}

const notifier = new Notifier(new EmailSender());

The Notifier now depends on anything with a send method, not on one concrete class. Testing gets easier too, because you can pass in a fake sender and check what it received. This is the principle behind dependency injection in most frameworks, and it is also why async code benefits from the same discipline: our guide on promises vs async await shows how clean boundaries make async code easier to test and change.

How to apply SOLID without overdoing it

These rules are guides, not laws. A small script does not need five interfaces, and splitting a class into ten pieces can make code harder to follow instead of easier. Apply SOLID where change is likely: the parts of the codebase you touch every week, the modules with the most bugs, and the areas where new requirements keep arriving. When you are unsure, ask one question: if this requirement changes next month, how many files would I have to edit? If the answer is more than one or two, one of the five principles above probably points at the fix. Start with Single Responsibility, since it is the easiest to apply and it makes the other four easier to see. Over time the principles stop feeling like rules and start feeling like habits, and the code you write next year will be easier to change than the code you wrote last year.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.