Skip to content
Velloreth
Programming 7 min read

SOLID Principles Explained With Practical Examples

SOLID is five design principles for maintainable object-oriented code. Learn each one with concrete examples of the problem it prevents.

By

What SOLID is

SOLID is an acronym for five design principles that aim at one goal: code that is easy to change.

The principles were described by Robert Martin and assembled into the acronym by Michael Feathers. They are guidelines, not laws, and they are most valuable in large codebases where change is frequent.

Each principle addresses a specific way code becomes hard to change. Understanding the problem each one prevents is more useful than memorising the definitions.

S — Single responsibility

A module should have one reason to change.

The common misreading is “a class should do one thing”. That is not it. The principle is about actors — the people or systems that request changes.

// Violates SRP: three different actors
class Employee {
  calculatePay(): number { /* finance rules */ }
  reportHours(): number { /* operations rules */ }
  save(): void { /* database concerns */ }
}

Three reasons to change: finance changes the pay rules, operations changes the hours report, and the database team changes the persistence. A change for one actor risks breaking the others.

The fix is to separate by actor:

class Employee { constructor(public data: EmployeeData) {} }

class PayCalculator {
  calculate(employee: Employee): number { /* finance */ }
}

class HoursReporter {
  report(employee: Employee): string { /* operations */ }
}

class EmployeeRepository {
  save(employee: Employee): void { /* database */ }
}

Now each class has one reason to change, and a change for finance cannot break the hours report.

The practical test: can you name the person or team who would request a change to this module? If there are two, it has two responsibilities.

O — Open-closed

Software entities should be open for extension but closed for modification.

You should be able to add new behaviour without editing existing, tested code.

// Violates OCP: every new shape edits this function
function area(shape: Shape): number {
  if (shape.type === 'circle') return Math.PI * shape.radius ** 2;
  if (shape.type === 'square') return shape.side ** 2;
  if (shape.type === 'triangle') return 0.5 * shape.base * shape.height;
  throw new Error('Unknown shape');
}

Adding a rectangle means editing area, which means re-testing every existing case.

// Follows OCP: new shapes are new classes
interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(private radius: number) {}
  area() { return Math.PI * this.radius ** 2; }
}

class Square implements Shape {
  constructor(private side: number) {}
  area() { return this.side ** 2; }
}

Adding a rectangle is a new class. Nothing existing changes.

The caveat: you cannot be closed against every change. The skill is identifying which changes are likely and designing for those. Premature abstraction against unlikely changes is worse than the problem it solves.

L — Liskov substitution

Objects of a subtype must be usable anywhere the supertype is expected.

If S is a subtype of T, then code written for T must work correctly with S.

class Rectangle {
  constructor(public width: number, public height: number) {}
  setWidth(w: number) { this.width = w; }
  setHeight(h: number) { this.height = h; }
  area() { return this.width * this.height; }
}

class Square extends Rectangle {
  setWidth(w: number) { this.width = this.height = w; }
  setHeight(h: number) { this.width = this.height = h; }
}
function testArea(rect: Rectangle) {
  rect.setWidth(5);
  rect.setHeight(4);
  console.assert(rect.area() === 20); // fails for Square: area is 16
}

Square is mathematically a Rectangle, but it is not substitutable. The subclass changed behaviour in a way callers cannot rely on.

The fix is to not use inheritance here. A Square has a side; a Rectangle has a width and height. They are different types.

The practical test: if you find yourself adding if (instanceof SubType) checks in code that takes the supertype, Liskov is violated.

I — Interface segregation

No client should be forced to depend on methods it does not use.

Fat interfaces force implementers to provide methods they do not need, usually as empty stubs or thrown errors.

// Violates ISP
interface Worker {
  work(): void;
  eat(): void;
  sleep(): void;
}

class Robot implements Worker {
  work() { /* ... */ }
  eat() { throw new Error('Robots do not eat'); }   // forced
  sleep() { throw new Error('Robots do not sleep'); } // forced
}

Robot is forced to implement methods that make no sense for it. Callers holding a Worker cannot know whether eat will work.

// Follows ISP
interface Workable { work(): void; }
interface Feedable { eat(): void; }
interface Restable { sleep(): void; }

class Robot implements Workable {
  work() { /* ... */ }
}

class Human implements Workable, Feedable, Restable {
  work() { /* ... */ }
  eat() { /* ... */ }
  sleep() { /* ... */ }
}

Now each type implements only what it can do, and callers depend only on what they use.

The practical test: if an implementation has methods that throw “not supported” or are empty, the interface is too fat.

D — Dependency inversion

High-level modules should not depend on low-level modules. Both should depend on abstractions.

This is the principle that makes code testable.

// Violates DIP: high-level policy depends on low-level detail
class OrderService {
  private db = new MySQLDatabase(); // concrete dependency

  placeOrder(order: Order) {
    this.db.insert('orders', order);
  }
}

OrderService is welded to MySQL. Testing it requires a real database. Switching to Postgres means editing the class.

// Follows DIP: both depend on an abstraction
interface OrderRepository {
  save(order: Order): Promise<void>;
}

class OrderService {
  constructor(private repository: OrderRepository) {}

  async placeOrder(order: Order) {
    await this.repository.save(order);
  }
}

class MySQLOrderRepository implements OrderRepository {
  async save(order: Order) { /* MySQL specifics */ }
}

Now OrderService depends on an interface. Tests pass a fake. Production passes MySQL. Switching databases means writing a new implementation, not editing the service.

The practical test: can you test this class without a database, network, or filesystem? If not, DIP is violated.

How the principles fit together

The five principles reinforce each other:

  • SRP gives you small, focused modules.
  • OCP lets you extend them without editing.
  • LSP ensures subtypes are safe to substitute.
  • ISP keeps interfaces small so implementations stay honest.
  • DIP decouples policy from detail, which makes everything testable.

The common thread is reducing the blast radius of change. Each principle limits how far a modification propagates.

When SOLID hurts

Applied dogmatically, SOLID produces over-engineering.

One class per method. Splitting everything into single-method classes produces a maze of indirection that is harder to follow than the original.

Interfaces with one implementation. If there is only ever one implementation and no test double, the interface is ceremony.

Abstraction before need. Designing for changes that never come adds complexity without benefit.

Small projects. A 500-line script does not need dependency injection and five layers of abstraction.

The judgement is: apply SOLID where change is likely and the codebase is large. In a small, stable module, clarity beats principle.

Practical guidance

  • Name the actor for each module — if there are two, split it.
  • Extend rather than modify where the extension point is clear.
  • Check substitutability before using inheritance.
  • Keep interfaces small and capability-focused.
  • Depend on abstractions at module boundaries.
  • Do not abstract prematurely — wait for the second or third case.
  • Remember these are guidelines, not rules to satisfy mechanically.

For the related design concepts, see interfaces vs abstract classes and composition vs inheritance. For the practical application, dependency injection without a framework and design patterns for beginners.

Quotable summary

SOLID is five principles aimed at code that is easy to change. Single responsibility means a module should have one reason to change, defined by the actor who requests changes rather than by the number of things it does. Open-closed means you should be able to add behaviour without editing existing code, usually through polymorphism. Liskov substitution means a subtype must be usable anywhere the supertype is expected, without breaking callers. Interface segregation means no client should depend on methods it does not use, which prevents fat interfaces and forced empty implementations. Dependency inversion means high-level policy and low-level detail should both depend on abstractions, which is what makes code testable. Applied dogmatically, the principles produce over-engineering, so they are guidelines for large, changeable codebases rather than rules.

Frequently asked questions

What does SOLID stand for?
Single responsibility, Open-closed, Liskov substitution, Interface segregation, and Dependency inversion. The acronym was coined by Michael Feathers from principles described by Robert Martin.
What is the single responsibility principle?
A module should have one reason to change, meaning it should serve one actor or stakeholder. It is not about doing one thing, but about having one source of change requests.
What is the open-closed principle?
Software entities should be open for extension but closed for modification. You should be able to add new behaviour without editing existing, tested code, usually by adding a new implementation of an interface.
What is the Liskov substitution principle?
Objects of a subtype must be usable anywhere the supertype is expected, without breaking correctness. If a subclass changes behaviour in a way callers cannot rely on, the inheritance is wrong.
What is the dependency inversion principle?
High-level modules should not depend on low-level modules; both should depend on abstractions. In practice this means depending on interfaces rather than concrete classes, which makes code testable and swappable.
Are SOLID principles still relevant?
Yes, though they are guidelines rather than laws. They are most valuable in large, long-lived codebases. Applied dogmatically to small projects they add ceremony without benefit.