SOLID Principles

Five principles for maintainable, extensible object-oriented design.

Cheat sheet

  • ▸S — Single Responsibility: one reason to change.
  • ▸O — Open/Closed: open for extension, closed for modification.
  • ▸L — Liskov Substitution: subtypes must be usable wherever the base type is.
  • ▸I — Interface Segregation: many small interfaces over one fat interface.
  • ▸D — Dependency Inversion: depend on abstractions, not concretions.
  • ▸Classic LSP violation: Square extends Rectangle.

SOLID at a glance

PrincipleSmell it fixesTypical fix
SRPGod classSplit classes
OCPGrowing if/else on typePolymorphism / strategy
LSPSubclass breaks expectationsRethink hierarchy
ISPEmpty method implementationsSplit interface
DIPnew inside business logicInject interfaces

Top 10 campus interview questions

Quick quiz

1. 'A class should have one reason to change' is:

2. Square extends Rectangle typically violates:

3. Depend on abstractions, not concretions:

4. Splitting a fat interface follows:

5. Adding a new class instead of editing a switch follows: