← JavaScript

Patterns & principles · 10 of 10 · 16 min read

SOLID in JavaScript

The five principles translated out of class diagrams into functions, modules and closures — including the two that change shape without interfaces.

  • Principles

SOLID was written for class-based, statically typed languages. JavaScript has no interfaces, no compile-time types and first-class functions, so three of the five translate directly, one changes shape, and one becomes almost trivial.

S — Single Responsibility

A module should have one, and only one, reason to change. A “reason to change” means a person or a department that can ask for something different — not a count of methods.

// Three reasons to change, in one class
class User {
  constructor(name, email) { this.name = name; this.email = email; }

  validate() { return this.email.includes('@'); }        // the product owner's rules
  save() { return db.insert('users', this); }            // the database schema
  sendWelcome() { return mailer.send(this.email, 'Hi'); } // the marketing copy
}

A change to the email template touches the same file as a change to the database schema, so the two are tested together, deployed together and conflict in review.

// One reason each
const user = (name, email) => ({ name, email });                 // the shape
const isValid = (user) => user.email.includes('@');              // the rules
const saveUser = (db, user) => db.insert('users', user);         // persistence
const sendWelcome = (mailer, user) => mailer.send(user.email, 'Hi'); // messaging

What it is not: a rule that functions must be short. A 60-line function that does one job is fine; a 6-line one that validates and saves is not.

O — Open/Closed

Open for extension, closed for modification. Adding a case should add code, not edit working code. In JavaScript the usual tool is not inheritance — it is a lookup you can register into.

// Closed to extension: every new type edits this function
function priceBad(type, total) {
  if (type === 'member') return total * 0.9;
  if (type === 'vip') return total * 0.8;
  return total;
}

// Open: adding a rule adds a key
const rules = new Map([['regular', (t) => t]]);
export const addRule = (name, fn) => rules.set(name, fn);
export const price = (type, total) => (rules.get(type) ?? rules.get('regular'))(total);

// in another file, with zero changes to the one above:
addRule('vip', (total) => total * 0.8);
console.log(price('vip', 100), price('unknown', 100)); // 80 100

The payoff is not elegance, it is blast radius: the pricing module keeps passing its tests because nothing in it was touched.

L — Liskov Substitution

Anything that accepts a type must work with any substitute for it, without knowing. A subclass or a second implementation may not strengthen what it demands or weaken what it promises.

// The classic violation: the subtype refuses something the base accepts
class Bird {
  fly() { return 'flying'; }
}
class Penguin extends Bird {
  fly() { throw new Error('penguins cannot fly'); } // breaks every caller of Bird
}

function migrate(birds) {
  return birds.map((b) => b.fly()); // correct against Bird, explodes on a Penguin
}

The fix is to model the ability rather than the taxonomy:

const canFly = (state) => ({ fly: () => `${state.name} flies` });
const canSwim = (state) => ({ swim: () => `${state.name} swims` });

const duck = { name: 'duck', ...canFly({ name: 'duck' }), ...canSwim({ name: 'duck' }) };
const penguin = { name: 'penguin', ...canSwim({ name: 'penguin' }) };

const flyers = [duck, penguin].filter((b) => typeof b.fly === 'function');
console.log(flyers.map((b) => b.fly())); // ["duck flies"] — nothing to throw

Without a type system, substitutability is about behaviour, and the cases are subtler than a thrown error:

// Same shape, incompatible contracts
const httpRepo = { findById: async (id) => null };            // missing → null
const cacheRepo = { findById: async (id) => { throw new Error('miss'); } }; // missing → throws

Both have findById. Code written against the first crashes on the second. That is a Liskov violation with no inheritance anywhere in sight — and it is why the contract test in the Repository page checks behaviour rather than shape.

I — Interface Segregation

No client should be forced to depend on methods it does not use. With no interface keyword, this becomes a rule about parameters: ask for the smallest thing that does the job.

// Demands an entire repository to read one name
function greet(userRepository, id) {
  return `Hi ${userRepository.findById(id).name}`;
}

// Demands a user
function greetBetter(user) {
  return `Hi ${user.name}`;
}

// Demands a string
function greetBest(name) {
  return `Hi ${name}`;
}

Each step down makes the function easier to call, easier to test and harder to break. The same rule applies to object parameters — destructure what you use, so the signature states it:

// The signature says "anything with these two"
function renderRow({ id, total }) {
  return `${id}: ${total}`;
}
console.log(renderRow({ id: 1, total: 9, secret: 'x', fifty: 'other fields' })); // "1: 9"

And to the objects you hand out: a consumer that only needs to read should not be given something it can write to.

function createCounter() {
  let count = 0;
  const increment = () => ++count;
  const read = () => count;

  return {
    writer: { increment },  // given to whoever counts
    reader: { read },       // given to whoever displays — it cannot increment
  };
}

const { writer, reader } = createCounter();
writer.increment();
console.log(reader.read(), reader.increment); // 1 undefined

D — Dependency Inversion

High-level modules should not depend on low-level modules; both should depend on abstractions. In a language without interfaces the abstraction is the shape you agree on, and the mechanism is passing it in rather than importing it.

// Inverted the wrong way: the policy reaches down and grabs its tools
import { postgres } from './postgres.js';
import { sendgrid } from './sendgrid.js';

export async function checkout(cart) {
  const order = await postgres.insert('orders', cart);   // welded to Postgres
  await sendgrid.send(cart.email, 'Thanks');             // welded to SendGrid
  return order;
}
// Inverted correctly: the policy states what it needs
export function createCheckout({ orders, mailer }) {
  return async function checkout(cart) {
    const order = await orders.save(cart);
    await mailer.send(cart.email, 'Thanks');
    return order;
  };
}

// main.js decides, once, what those are:
const checkout = createCheckout({ orders: postgresOrders, mailer: sendgridMailer });

// and a test decides something else, with no mocking library:
const saved = [];
const test = createCheckout({
  orders: { save: async (c) => (saved.push(c), { id: 1 }) },
  mailer: { send: async () => {} },
});
await test({ email: 'a@b.c' });
console.log(saved.length); // 1

checkout now depends on “something with save”, which is the abstraction. Nothing is imported, so nothing has to be intercepted to replace it.

Inversion and injection are not the same thing, and interviewers like that distinction:

What it is
Dependency Inversion the principle: depend on an abstraction, not on a concrete module
Dependency Injection one technique for it: hand the dependency in as an argument
A DI container a library that does the handing in. Rarely needed in JavaScript

You can inject and still not invert — passing in a concrete PostgresClient and calling client.query(sql) is injection with the coupling intact.

The five, at a glance

Classic form In JavaScript
S one reason to change per class per module or function — unchanged
O extend by subclassing extend by registering into a lookup
L subtypes substitute for base types any implementation of a shape must behave the same
I many small interfaces ask for the narrowest value you actually use
D depend on interfaces pass dependencies in; do not import them

Common mistakes

Reading S as “small”

Mistake. Splitting a coherent 60-line function into six 10-line ones to satisfy the letter. Why it fails. Six functions with one caller each is one function with five extra names and a jump for the reader. The reasons to change did not decrease. What to do instead. Split on who asks for the change, not on line count.

Applying O before the second case exists

Mistake. A registry and an extension point for a single implementation. Why it fails. The extension point is shaped by a guess, and the real second case arrives needing something else. What to do instead. Write the if. Open it up when the third case shows you the seam.

Calling it Dependency Inversion because something was passed in

Mistake. function save(postgresClient, row) { postgresClient.query(...) }. Why it fails. The argument is a concrete client and the call speaks SQL, so the module is still welded to Postgres. The parameter moved the import, not the dependency. What to do instead. Depend on a shape you defined — orders.save(order) — and let the Postgres version be one implementation of it.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

What does the Open/Closed principle ask for?

What does the Liskov Substitution principle require?

JavaScript has no interface keyword. What does Interface Segregation mean here?

Dependency Inversion and Dependency Injection get used interchangeably. What is the difference?

Practise Principles →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.