
Abstraction: The Rule Of Three - deveac
http://lostechies.com/derickbailey/2012/10/31/abstraction-the-rule-of-three/
======
B-Con
Summarized: When writing code,

> If you need something once, build it. If you need something twice, pay
> attention. If you need it a third time, abstract it.

I like this rule. Pre-mature re-factoring is a cousin of pre-mature
optimization. Having similar code in two places isn't a problem if similar
functionality is required in two places. By the time you need it in three
places, you don't need similar functionality so much as you need to utilize an
abstracted pattern.

Not a hard-and-fast rule, but it's something I personally have tended to
gravitate toward myself over time. I used to be more aggressive at
refactoring, but now I tend to favor re-using code when re-factoring is not
_clearly_ called for.

------
glyphobet
This is a bit too simplistic. The rule of three really should apply to similar
patterns that emerge naturally in the course of implementation.

His example code consists of two four-line functions that share a common if-
else control structure but call totally different functions. That's not
copied-and-pasted code, and it's not enough similarity to warrant
generalization even after three or four replications. (And it would be better
modularized away completely using inheritance or delegation, instead of a
state machine.)

When it comes to copying and pasting _identical_ blocks of code that actually
_do_ something, even having two copies opens you up to copy-and-paste bugs.
Waiting until you have a third copy is too late. Don't ever copy and paste.

------
OhArgh
Anyone else having issues accessing this link?

~~~
cpdean
google cache:
[http://webcache.googleusercontent.com/search?q=cache:http://...](http://webcache.googleusercontent.com/search?q=cache:http://lostechies.com/derickbailey/2012/10/31/abstraction-
the-rule-of-three/)

