SOLID Principles — Clean Code

SOLID (collected by Robert C. Martin, acronym by Michael Feathers) is five design principles: Single Responsibility, Open/Closed, Liskov Substitution…

The electricity in your house has long followed the five rules you'll learn here. One switch for one lamp (S). A new fan just plugs in, without opening the wiring in the wall (O). A plug that says it fits has to actually power the appliance, not cause a short circuit (L). The socket asks for two pins, not five pins the appliance never uses (I). And the house wiring depends on the standard socket shape, not on one brand of fan (D).

In code, the five are called SOLID, design principles that keep code cheap to change: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion. Robert C. Martin collected them in the paper "Design Principles and Design Patterns" (2000), and Michael Feathers later made the acronym SOLID from their first letters.

Five principles, five changes in the checkout

Each principle is easiest to understand from the change that gets expensive when it is broken. This table pairs each letter with one change in Raka's checkout:

Principle Change in Raka's checkout Without the principle
S customer service changes the email greeting opening the method that also holds the price formula
O adding the SAVE20 voucher editing a working switch, which can break SAVE10
L member carts with free shipping Total: $0.00 for every member
I marketing adds a promo method 3 notifier classes change, the checkout changes nothing
D testing placeOrder 4 checks send 4 real emails

S: one reason to change

This principle was covered in the Single Responsibility lesson. In the electricity picture, it is one switch for one lamp: one unit of code for one reason to change. An OrderService.placeOrder that validates, prices, saves and sends email has five parties who can ask for changes. Once it is split by who asks, customer service's request only touches OrderMailer. In the exercise, UserService only handles user data and EmailService only sends email, so UserService.prototype.sendEmail (the sendEmail method of UserService) must be undefined.

O: add without changing

Open/Closed (Bertrand Meyer, Object-Oriented Software Construction, 1988): code is open for extension, closed for modification. This means new behaviour is added by adding code, not by editing code that already works. In the electricity picture, new code is the fan that just plugs in, and the code that already works is the wiring in the wall. Without this principle, SAVE20 means editing a switch:

function discountRate(voucherCode) {
  let rate = 0;
  switch (voucherCode) {
    case 'SAVE20': rate = 0.2;      // new line, forgot break
    case 'SAVE10': rate = 0.1; break;
  }
  return rate;
}

Here is the check for cart A with SAVE20:

DIFF Total: $220.50, expected Total: $211.00

Without break, JavaScript goes on to run the next branch. So SAVE20 "falls through" into the SAVE10 branch, and its rate is overwritten with 0.1. Editing a function that works can always break it. The VOUCHERS table from the Refactoring Techniques lesson and the voucher classes from the Refactoring Patterns lesson are already closed for modification. SAVE20 is one new entry, SAVE20: new PercentVoucher(0.2), and zero old lines change. Another example, from the exercise: calculateArea(shape) only calls shape.area(), so a new shape doesn't change that function.

L: a subclass keeps its parent's promise

Liskov Substitution (Barbara Liskov, 1987): an object of a subclass (a class made with extends) must work wherever its parent works, without the caller noticing a difference. In the electricity picture, a subclass is a plug that says it fits: if it claims to be a Cart, it has to work like a Cart. The promise of Cart.addShipping(amount) is to return amount plus shipping.

class Cart {
  constructor(items) { this.items = items; }
  subtotal() { let s = 0; for (const item of this.items) s += item.price * item.qty; return s; }
  addShipping(amount) { return amount < FREE_SHIPPING_MIN ? amount + SHIPPING_FEE : amount; }
}
class FreeShippingCart extends Cart {   // a member's cart
  addShipping() { return 0; }           // "the shipping is zero"
}

function calculateTotal(cart, voucherCode) {
  const discounted = applyVoucher(cart.subtotal(), voucherCode);
  return 'Total: ' + formatPrice(cart.addShipping(discounted));
}

FreeShippingCart is the member cart, which has free shipping. Here is the check for a member's cart C:

DIFF Total: $0.00, expected Total: $75.00

$0.00, with no error. The subclass's author thought addShipping returns the fee, but its promise is to return the total. As a result, every member shops for free. The fix keeps the promise: addShipping(amount) { return amount; }. Member cart C becomes Total: $75.00, and member cart D with SAVE10 becomes Total: $189.00.

A more precise rule comes from Liskov and Wing (1994). A subclass:

The classic example is Square extends Rectangle, a square as a kind of rectangle. Code that sets the width to 5 and then the height to 4 expects an area of 20. A square changes its width and height together, so when the height is set to 4, the width becomes 4 too, and the result is 16.

I: ask only for what you use

Interface Segregation (Martin): whoever uses a contract must not be forced to depend on methods it doesn't use. A contract, often called an interface, is the list of methods every class that fulfils it must have. In the electricity picture, the contract is the socket and its methods are the pins. The checkout's Notifier (notification sender) contract asks for four methods: sendConfirmation, sendSms, sendWhatsapp, sendPromo. OrderService only calls sendConfirmation, yet its test fake has to write them all:

class FakeNotifier {
  constructor() { this.sent = []; }
  sendConfirmation(order) { this.sent.push(order.id); }
  sendSms() {}        // forced by the contract, never called
  sendWhatsapp() {}   // forced by the contract, never called
  sendPromo() {}      // forced by the contract, never called
}

When marketing adds sendPromoWithVoucher to the contract, EmailNotifier, WhatsappNotifier and FakeNotifier all change. That is 3 classes touched, while the checkout changes nothing. The fix is to split the contract: OrderService asks for an OrderNotifier (only sendConfirmation), and the promo module asks for a PromoSender (only sendPromo). JavaScript has no interface keyword. The contract is written in a JSDoc @typedef (a tag that gives a name to a shape of object) or in a TypeScript interface. TypeScript is JavaScript with types, checked before the code runs, and it is TypeScript that rejects a class that is missing a method.

D: depend on a contract, not on real email

Dependency Inversion (Martin): high-level modules (the checkout's rules) don't depend on low-level modules (how email is sent). Both depend on an abstraction, here "anything that has sendConfirmation(order)". In the electricity picture, OrderService is the house wiring, sendConfirmation(order) is the standard socket shape, and EmailMailer is the fan.

The second part of the principle: abstractions do not depend on details (here EmailMailer); details depend on abstractions. What is "inverted" is who owns the contract. OrderService decides its shape, sendConfirmation(order), and EmailMailer adapts to it. If the shop moves to WhatsApp, the new sender class writes sendConfirmation(order). OrderService does not change.

class OrderService {
  constructor(mailer) { this.mailer = mailer; }   // received from outside
  placeOrder(cart, voucherCode, email) {
    const order = { id: 1, email, total: calculateAmount(cart, voucherCode) };
    this.mailer.sendConfirmation(order);
    return order;
  }
}

const fake = { sent: [], sendConfirmation(order) { this.sent.push(order.total); } };
const service = new OrderService(fake);              // in the test
// new OrderService(new EmailMailer())               // in the real shop

The old version wrote new OrderMailer().sendConfirmation(order) inside placeOrder, so the four cart checks sent 4 real emails. This version takes the mailer from outside. With the fake, 0 emails are sent, and fake.sent holds [220.5,245,90,204], the totals of the four carts. Passing a dependency (another object a class needs, here the mailer) in from outside through the constructor like this is called Dependency Injection. It is a technique for carrying out the principle of Dependency Inversion.

Exercise: UserService, EmailService and Circle

The output is four lines. The last one, true, means UserService has no sendEmail:

{"id":1,"name":"User 1"}
Email sent to [email protected]: Welcome
153.93804002589985
true

⚠️ SOLID memorised, not used

TL;DR: SOLID (collected by Robert C. Martin, acronym by Michael Feathers) is five design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion. Each principle keeps one kind of change cheap. S: one reason to change, so changing the email greeting doesn't touch the price formula. O: open for extension, closed for modification. SAVE20 added to a switch without break makes cart A come to $220.50, not $211.00, while a new table entry or class changes zero old lines. L: a subclass (a class made with extends) keeps the promise of its parent's methods about what they return. In the member cart with free shipping, a FreeShippingCart.addShipping returning 0 makes Total: $0.00, while the right one returns amount. I: a contract (an interface, the list of methods a class must have) asks only for the methods that are used, so a fake for the tests doesn't need three empty methods. D: depend on an abstraction, not on a real email sender. Dependency Injection (passing the email sender through the constructor) is the technique, and a test with a fake sends 0 emails. In the exercise: UserService without sendEmail, EmailService returning Email sent to [email protected]: Welcome, and Circle(7).area() with Math.PI giving 153.93804002589985.

⚡ Five letters, five changes

Meaning: SOLID is five design principles that keep code cheap to change: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion. Each principle is easiest to understand from the change that gets expensive when it's broken.

⚡ O: add without changing

Write:

  switch (voucherCode) {
    case 'SAVE20': rate = 0.2;      // new line, forgot break
    case 'SAVE10': rate = 0.1; break;
  }
Guess first: a new SAVE20 line is added to a working switch, and its break is forgotten. Cart A with SAVE20 should be Total: $211.00. With this switch, what is it?

Total: $220.50. Without break, SAVE20 "falls through" into the SAVE10 branch, and its rate is overwritten with 0.1.

Meaning: Open/Closed: code is open for extension (additions), closed for modification (changes). So SAVE20 is one new entry in the voucher table, SAVE20: new PercentVoucher(0.2) (the percentage voucher class), with no old line edited.

⚡ L: a subclass keeps its parent's promise

Write:

class FreeShippingCart extends Cart {   // a member's cart
  addShipping() { return 0; }           // "the shipping is zero"
}
Guess first: FreeShippingCart is the member cart, a subclass of Cart. The promise of Cart.addShipping(amount): it returns the total plus shipping, and the checkout shows the result as the final total. What does a member's cart C ($75) come to?

Total: $0.00, with no error. The subclass's author thought addShipping returns the fee, so every member shops for free. The right one is addShipping(amount) { return amount; }.

Meaning: Liskov Substitution: an object of a subclass (a class made with extends) must work anywhere its parent is used, without the caller noticing a difference. So a subclass has to keep the promise of its parent's methods.

⚡ I and D: ask for what you use, take it from outside

Write:

const fake = { sent: [], sendConfirmation(order) { this.sent.push(order.total); } };
const service = new OrderService(fake);              // in the test

Meaning: fake is a stand-in email sender for the tests: it only records each order's total in sent. OrderService only asks for "anything that has sendConfirmation" (I: the contract it asks for has only one method), and the email sender (the mailer) is passed in through the constructor (D, with the technique called Dependency Injection). The test uses a fake, so 0 emails go out.

What you will learn