SOLID Principles
SOLID is a set of five design principles for writing object-oriented code that handles change well. Code that doesn't follow them tends to get fragile — a small change in one place breaks five others. SOLID code stays flexible.
S — Single Responsibility
A class should have one reason to change. If your Invoice class computes totals, prints to a printer, AND saves to a database, then a printer-format change forces a recompile of code that has nothing to do with printing. Split it into Invoice, InvoicePrinter, and InvoiceRepository.
O — Open/Closed
Classes should be open for extension, closed for modification. You should be able to add new behavior without editing existing classes. Polymorphism is the main tool here — adding a new Notifier subclass doesn't require touching the existing alert function.
L — Liskov Substitution
If B is a subclass of A, anywhere code uses an A, you should be able to substitute a B without breaking anything. The classic violation: making Square a subclass of Rectangle and overriding setWidth to also change height — code expecting rectangle behavior breaks.
I — Interface Segregation
Don't force classes to implement methods they don't need. Many small, focused interfaces beat one big interface. A Printer shouldn't have to implement scan() and fax() just because it's typed as a MultiFunctionDevice.
D — Dependency Inversion
High-level code should depend on abstractions, not on concrete classes. Instead of your OrderService directly creating an EmailNotifier, it should accept any Notifier from the outside. This makes testing easier (swap in a fake) and changing technology trivial (swap in SMS).
How They Work Together
These principles reinforce each other. SRP keeps classes small. OCP and LSP make extending them safe. ISP keeps abstractions tight. DIP wires it all together with loose coupling.
Try It Yourself
- Refactor a class that does file I/O, validation, and business logic into three classes
- Add a third notifier (Slack, push, etc.) without modifying the
alertfunction - Find a class in your code with five public methods and ask: does it have one responsibility?