Chapter 7

AHA: Avoid Hasty Abstractions

AHA - "Avoid Hasty Abstractions." An abstraction is good when we already understand a stable common regularity. Generalize the code too early and instead of a convenient tool you get a mechanism of flags, exceptions, and parameters - harder to read than the two simple pieces it grew from.

Sometimes it's safer to keep two simple implementations for a while. Real changes will show what they truly share and what was only skin-deep similarity. This directly continues Sandi Metz's thought: duplication is cheaper than the wrong abstraction - because it's easy to extract the shared part from a duplicate later, but hard to escape a wrong abstraction.

An abstraction is earned, not assigned. A reliable shared part is one that survived several real changes and stayed shared. While the change history is short, wait: an abstraction extracted too early binds things that should have diverged.

To see whether it's time to generalize, use the lab - it looks not at similarity but at the number of changes survived.

Interactive lab 3

Is it time to abstract?

Early: keep two simple implementations. An abstraction now would bind what should diverge.
Knowledge check

When is an abstraction reliable per AHA?

Now we have both DRY and AHA - and they often argue with KISS. That conflict deserves its own chapter.

Links