Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 4
Module 3 · Design principles and patterns · Chapter 4 of 28
Design Principles: SOLID, DRY, KISS, YAGNI and the Law of Demeter
Builds on Cornerstones of OOP in TypeScript: Encapsulation, Abstraction, Inheritance, Polymorphism. Next up: Design Patterns in TypeScript: Creational, Structural and Behavioural.
Part 1 · Single responsibility
One group of people, one module
A co-working space changes its tax line, its invoice layout and its discount rules every few months, and each change comes from a different person. Code that survives this is organised around who asks for the change.
The single responsibility principle (SRP) says a module should have one reason to change. The common shortcut, "a class should do one thing", is too vague to apply: almost any class can be described as doing one thing at some level of detail. Robert C. Martin's 2014 write-up of the principle makes it concrete by tying each reason to a person. A module should answer to one stakeholder or one tightly coupled group, and the principle is about people, not about technical activities such as fixing bugs or refactoring.
A stakeholder here is whoever can legitimately ask you to change a behaviour: the finance team for a tax rule, the operations team for the layout of a printed invoice, the platform team for where invoices are stored. When two of them edit the same class, each edit risks breaking something the other one cares about. SRP is the habit of cutting code along those lines, so that a request from one group lands in one place.
The first five principles of this chapter are known together as SOLID, from their initials: single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion. The last two lessons cover DRY, KISS, YAGNI and the Law of Demeter, which are shorter rules of thumb.