Skip to content

1 · 32 · 5 min

The function that ate a team

A student writes a small function to send a notification.

java
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

ToolWhat it lets you do
EncapsulationChange how something works without breaking its users
AbstractionDepend on what something does, not how
InheritanceShare behaviour without copying it
PolymorphismAdd a case without editing the chooser

The last one is the fix for the function above, and by page eight you will write it.