SOLID Principles Summary
The five SOLID principles in one place: what each one asks for, how they depend on each other, and one small example that shows all five.
Overview
SOLID is a set of five rules for arranging classes so that a program stays easy to change. Robert C. Martin collected them in the late 1990s; his 2000 paper 'Design Principles and Design Patterns' explains four of them (OCP, LSP, DIP, ISP) and the problem they solve, which he calls software rot. The acronym came later, around 2004, and is credited to Michael Feathers.
Every principle is about change. Martin's paper names four signs of a design that has started to rot, and each principle removes one or more of them.
- Rigidity: one small change forces changes in many modules. A common cause is classes that depend directly on each other.
- Fragility: a change breaks code that seems unrelated. Often one class does several jobs, so its parts share state.
- Immobility: a useful class cannot be reused because it drags its dependencies along. It usually depends on concrete details.
- Viscosity: the hack is easier than the clean change, because the design gives no clean place to add behavior.
The five principles
Each letter names one principle, and each comes with a question you can ask about your own code.
- S, Single Responsibility (SRP): gather what changes for the same reason, and separate what changes for different reasons. Ask who requests changes to this class, and whether it is more than one group.
- O, Open-Closed (OCP): a module is open for extension and closed for modification. Ask whether you can add a new case without editing existing classes.
- L, Liskov Substitution (LSP): code that uses an interface must not be confused by an implementation of it. Ask whether any subtype can stand in for the base type without surprises.
- I, Interface Segregation (ISP): keep interfaces small, so users do not depend on what they do not need. Ask whether every implementer uses every method.
- D, Dependency Inversion (DIP): depend in the direction of abstraction, not on low-level details. Ask whether the business logic imports the database, or an interface.
The 'L' is named for Barbara Liskov. In a 1987 talk she described the idea as a substitution property: if a program written against type T behaves the same when objects of type S replace objects of type T, then S is a subtype of T. Liskov and Jeannette Wing made the rule precise in 1994.
Interview questions
- This class computes a report, formats it and saves it. Which principle does it break, and how would you fix it?
- How do the Open-Closed and Dependency Inversion principles work together?
- Show a Liskov Substitution violation that runs without errors but is still wrong.
- When should you not apply a SOLID principle?
- Do SOLID principles apply outside a single class, for example to services?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio