1 · 32 · 5 min
The function that ate a team
A student writes a small function to send a notification.
void send(String type, String to, String body) {
if (type.equals("email")) {
// 20 lines of SMTP
}
}It works. Two weeks later, SMS is added, so an else if goes in. Then push notifications. Then WhatsApp.
Six months on the function is 200 lines, four people have edited it, and every time somebody adds a channel, SMS breaks. Nobody can say why. The SMS code has not changed.
What went wrong
Nothing, in any single edit. Every one of them was the smallest reasonable change. The problem is the shape of the code, not any line in it: adding something new requires editing something that works.
That is the entire subject. Objects are not about modelling the real world, despite every textbook opening with a Dog that extends Animal. They are about making that sentence false.
The four tools
| Tool | What it lets you do |
|---|---|
| Encapsulation | Change how something works without breaking its users |
| Abstraction | Depend on what something does, not how |
| Inheritance | Share behaviour without copying it |
| Polymorphism | Add a case without editing the chooser |
The last one is the fix for the function above, and by page eight you will write it.