SOLID in Plain Words
Five pieces of advice with a famous acronym, each with an everyday picture and a before-and-after. Advice, not law: the chapter ends each one with when to bend it.
Updated
SOLID
- Single Responsibility: One Reason to Change (Apprentice): When one class works out the grades, lays out the report card and emails it, three different people's changes all land in the same class and can break each other; the first SOLID principle, single responsibility, says to give each class one reason to change, and this lesson opens with what SOLID is and where it came from.
- Open/Closed: Add, Don't Edit (Apprentice): When every new grading scale means editing the grade function that the whole school trusts, each new scale risks breaking the old ones; the open/closed principle says to leave working code closed to edits and open to additions, so a new scale is a new class that keeps a promise, and the grade code never changes.
- Liskov Substitution: No Surprises from a Stand-In (Journeyman): When a pass/fail course is written as a kind of course and then throws when asked for a letter grade, every report card with art on it stops; the Liskov substitution principle says a subclass must keep every promise its parent makes, so it can stand in anywhere the parent is expected, with no surprises.
- Interface Segregation: Small Promises (Journeyman): When one big promise makes every course answer for attendance, labs and a final exam, a course with no labs has to fake its answers, and the fakes end up on the lab report; the interface segregation principle says to make small promises, so each class keeps only what it can and each piece of code asks only for what it uses.
- Dependency Inversion: Depend on the Promise (Journeyman): When the report-card sender builds the school's email server inside itself, it can never send a text and can never be tested without sending real email; the dependency inversion principle says the report card should depend on a promise it owns ("a way to send"), and be handed whatever keeps it, which is the start of dependency injection.
Exercise: The Report Card Printer
- Exercise: The Report Card Printer (Apprentice): Take the front office's ticket: some families want report cards by text message, the tests must stop going through the real email server, and one class is doing three people's jobs. Change the working report-card code so any sender can be handed in, with the tests green throughout.