Find a course

Module 4: Composition and Design PrinciplesLesson 10 of 1215 min

The SOLID Principles

Apply the five SOLID principles (single responsibility, open-closed, Liskov, interface segregation, dependency inversion) to real class designs.

Step 1 of 14Learn

Five guidelines with one goal

In the early 2000s, a set of object-oriented design guidelines popularized by software engineer Robert C. Martin became known by the acronym SOLID:

  • Single responsibility principle
  • Open-closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle

They share one goal: make code easy to change. Requirements always shift, and a design that forces you to edit ten classes for one small feature slows every future change and invites bugs.

Treat them as guidelines for judgment, not laws to follow mechanically. A 200-line script doesn't need five interfaces. The principles earn their keep in long-lived code that many people work on.

Single responsibility (SRP): a class should have only one reason to change. "Reason to change" means a source of change requests, often a group of people. Consider an Employee class with calculatePay(), formatPayslipHtml() and saveToDatabase(). The payroll team changes pay rules, the design team changes payslip layout, and the database team changes storage. Three reasons to change in one class means three teams stepping on each other's edits. Splitting it into PayCalculator, PayslipFormatter and EmployeeRepository gives each change one home.

SRP is cohesion seen from a different angle: a class with one job is cohesive, and a cohesive class has one reason to change.

Step 2 of 14Practice · Choose one

A Report class gathers sales data, calculates totals, formats the result as a PDF and emails it to managers. Which change best applies the single responsibility principle?

Step 3 of 14Diagram

Single responsibility: one class per reason to change

Single responsibility: one class per reason to changeHierarchy diagram: Employee (three reasons to change), PayCalculator, PayslipFormatter, EmployeeRepository.Employee (threereasons to change)PayCalculatorPayslipFormatterEmployeeRepository

Tap a shape with to see more.

Employee (three reasons to change)
PayCalculator

Changed by the payroll team.

PayslipFormatter

Changed by the design team.

EmployeeRepository

Changed by the database team.

Step 4 of 14Learn

Open-closed: extend without editing

The open-closed principle (OCP) says software should be open for extension but closed for modification. In practice: you should be able to add new behavior by adding new code, not by editing code that already works and is already tested.

Here is a violation:

function shippingCost(order) {
  switch (order.method) {
    case 'standard': return 5;
    case 'express':  return 15;
    case 'drone':    return order.weight < 2 ? 25 : null;
  }
}

Every new shipping method means opening this function and editing it, risking the existing cases. The OCP version uses polymorphism:

class StandardShipping { cost(order) { return 5; } }
class ExpressShipping  { cost(order) { return 15; } }
class DroneShipping    { cost(order) { return order.weight < 2 ? 25 : null; } }

function shippingCost(order, method) { return method.cost(order); }

A new method, say LockerShipping, is a new class. shippingCost never changes.

Don't apply OCP everywhere in advance. Guessing every future variation produces layers of abstraction nobody needs. A practical habit: write the simple version first, and when the second or third variation arrives and you find yourself editing the same switch again, refactor toward polymorphism then.

Liskov substitution (LSP), the L, you met in the previous module: subclasses must honor their parent's contract. It's what makes OCP safe, because new subclasses can be plugged in without breaking callers.

Step 5 of 14Practice · Spot the mistake

This discount code is meant to follow the open-closed principle, so new customer types can be added without editing existing code. Click the lines that violate it.

Step 6 of 14Compare

Adding LockerShipping: switch vs strategy classes

AspectOne switch statementOne class per method
To add a methodEdit shippingCost()Write class LockerShipping
Tested code edited?Yes, every timeNo
Risk to existing casesA typo can break standard or expressNone: they are untouched
When it is fineOne or two stable casesThe second or third variation has arrived

Step 7 of 14Learn

Interface segregation: small, focused contracts

The interface segregation principle (ISP) says clients should not be forced to depend on methods they don't use. Big "do everything" interfaces force every implementer to provide methods that make no sense for it.

interface Machine {
  print(doc): void;
  scan(doc): void;
  fax(doc): void;
}
class BasicPrinter implements Machine {
  print(doc) { /* ... */ }
  scan(doc) { throw new Error('Not supported'); }
  fax(doc)  { throw new Error('Not supported'); }
}

The basic printer must pretend to scan and fax, and it fails at run time if anyone tries. The split version uses small interfaces: Printer, Scanner, Fax. A basic printer implements Printer; an office machine implements all three. Code that only prints depends only on Printer.

Those throw new Error('Not supported') methods should look familiar: they're also an LSP violation. The principles reinforce each other.

Dependency inversion (DIP): high-level code should not depend on low-level details; both should depend on abstractions. An OrderService that creates new MySqlDatabase() inside itself is welded to MySQL. Instead, it should depend on an abstraction such as OrderRepository (anything with save(order) and findById(id)) and receive the real implementation from outside:

class OrderService {
  constructor(repository) { this.repository = repository; }
  place(order) { /* business rules */ this.repository.save(order); }
}
new OrderService(new SqlOrderRepository());     // production
new OrderService(new InMemoryOrderRepository()); // tests

Passing collaborators in through the constructor is called dependency injection, the most common way to apply DIP.

Step 8 of 14Practice · Match the pairs

Match each SOLID principle to the problem it addresses.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Single responsibility
  2. Open-closed
  3. Liskov substitution
  4. Interface segregation
  5. Dependency inversion

Step 9 of 14Diagram

SOLID at a glance

SOLID at a glanceParts diagram: SOLID: easy to change, S: single responsibility, O: open-closed, L: Liskov substitution, I: interface segregation, D: dependency inversion.SOLID: easy tochangeS: singleresponsibilityO: open-closedL: LiskovsubstitutionI: interfacesegregationD: dependencyinversion

Tap a shape with to see more.

SOLID: easy to change
S: single responsibility

One reason to change per class.

O: open-closed

Add behavior with new code, not edits.

L: Liskov substitution

Subclasses keep the parent's promises.

I: interface segregation

Small interfaces; no fake "not supported" methods.

D: dependency inversion

Depend on abstractions; inject the details.

Step 10 of 14Practice · Code challenge

Apply dependency inversion. Rewrite WelcomeService so that it receives its sender through the constructor instead of creating one itself. welcome(name) should call this.sender.send("Welcome, " + name + "!") and return whatever send returns. The tests pass in a fake sender.

Runs in a sandbox in your browser.
  • new WelcomeService({ send: (t) => t }).welcome("Kai")
  • new WelcomeService({ send: (t) => t.length }).welcome("Al")
  • (() => { const sent = []; const s = new WelcomeService({ send: (t) => { sent.push(t); return true; } }); s.welcome("A"); s.welcome("B"); return sent; })()

Step 11 of 14Learn

SOLID in a small example

Here is how the principles combine in one realistic change. An online shop computes order totals in a single OrderProcessor class that also applies discounts, charges a card through a vendor library and writes a receipt file.

The product team asks for two things: a new "student" discount and a switch to a different payment provider.

In the original design, both requests mean editing OrderProcessor, which is already 600 lines long and has no tests because it charges real cards.

A SOLID-shaped redesign:

  • SRP: split into PriceCalculator, PaymentGateway and ReceiptWriter, each with one job.
  • OCP: discounts become strategy objects. The student discount is a new class; PriceCalculator isn't edited.
  • LSP: every discount honors the same contract: it never returns a negative price.
  • ISP: PaymentGateway exposes only charge(amount, card); the vendor's 40 other methods stay hidden behind an adapter.
  • DIP: the order service receives a PaymentGateway in its constructor, so switching providers means writing one new adapter and changing one line at startup. Tests pass a fake gateway.

Each request now touches one small, testable class. That's the practical promise of SOLID.

Step 12 of 14Practice · What would you do?

What would you do?

After the redesign above, the shop wants to add a "loyalty points" discount. Which change fits the open-closed principle?

Step 13 of 14Note

Step 14 of 14Practice · True or false

Dependency injection means a class creates all of its own collaborators inside its constructor, so callers don't have to know about them.