Hacker News new | past | comments | ask | show | jobs | submit login
Abstraction: The Rule Of Three (lostechies.com)
17 points by deveac on Nov 1, 2012 | hide | past | favorite | 6 comments



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.


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.


Anyone else having issues accessing this link?



site is back up now


site seems to be down. too much traffic maybe?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: