Skip to main content

SOLID principles

Five design principles, collected by Robert Martin, aimed at making designs more understandable, flexible and maintainable. The letters spell a mnemonic:

Applied mindlessly, they cause more harm than good. Every one of them buys flexibility with indirection, and there is probably no successful product where all five are applied everywhere at once. Strive for them, stay pragmatic, and treat none of it as dogma - each page linked above ends with the cases where that principle is the wrong tool, the design patterns in this site's catalog that exist mainly to satisfy it, and a second worked example in a different domain so the idea does not stay welded to one story.

None of the five stand alone, either. Open/closed usually gets satisfied by reaching for Strategy or Decorator; dependency inversion is what Dependency Injection is for; a class that violates single responsibility is often also the class that turns out hardest to keep open/closed, because two reasons to change means two chances for a new requirement to force a rewrite instead of an extension. Read them in order once, then treat each page as a reference to come back to.

Spot the smell

Five snippets, each lifted straight from the "where it goes wrong" examples across the five pages above. Pick which principle each one breaks before checking your work.

Snippet 1 of 5
// Employee knows two entirely unrelated things:
// what an employee is, and what a timesheet report looks like.
class Employee is
field name: string
field hourlyRate: number
field hoursWorked: list of entries
 
method getName() is
return name
 
method setName(name) is
this.name = name
 
// ...and then, for no structural reason, printing:
method printTimeSheetReport() is
print("TIMESHEET FOR " + name.toUpperCase())
print("--------------------------------")
foreach entry in hoursWorked
print(entry.date + " " + entry.hours + "h")
print("--------------------------------")
print("TOTAL: " + sum(hoursWorked) + "h")
 
// Two reasons to change, in one file:
// 1. the HR system changes how employees are modelled
// 2. someone in finance wants the report in CSV
0%0 of 154 pages studied