-
Abstraction layers: One, two, many
-
(cc) by piet_musterdIt’s becoming pretty clear to me that when in doubt whether to write an abstraction, the rule is clear: “one, two, many”.
Write something 3 times and you’re breaking the DRY principle. The cost of changing a bit in one place and needing to update the other places too is high.
Abstract something you only use once (in case you want to re-use in the future), and you forgot the “two” in the above rule. The cost for later refactoring is probably not worth the extra load you’ll carry until that day comes. If it comes.
“One, two, many” is usually better than “one, two, three” and “one, many”.
Very true. There’s another advantage to waiting until the third time: after you’ve only done something once, your level of experience with the usage probably isn’t broad enough to make an abstraction that really works well. It will either be over-generalised — usually resulting in over-complicated — or too restrictive.
Sometimes, though, you end up tweaking version one so often that the only reason you’re writing version two is to stop all the tweaking, meaning abstraction probably is the right moment. But that’s more a case of needing to count one, two, three differently. I do agree with your rule of thumb, though. Only to be broken when there are good reasons that you can explain to somebody else.