17

I just came across the article "Rule of Three" in wikipedia

Rule of three is a code refactoring rule of thumb to decide when a replicated piece of code should be replaced by a new procedure. It states that the code can be copied once, but that when the same code is used three times, it should be extracted into a new procedure. The rule was introduced by Martin Fowler in Refactoring and attributed to Don Roberts.

I know that this is just a rule of thumb, but why is it recommended to refactor only after the second duplication? Is there any downside to refactoring when we write the first duplication?

Louis Rhys
  • 6,042
  • 11
  • 42
  • 59
  • 3
    See [Two is an impossible number](http://c2.com/cgi/wiki?TwoIsAnImpossibleNumber) and [Zero-One-Infinity rule](http://c2.com/cgi/wiki?ZeroOneInfinityRule) for another set of perspectives. – AakashM May 08 '13 at 08:27
  • 2
    When talking about software development, the *original* Wiki is often a much better source than Wikipedia. After all, Ward Cunningham *invented* the Wiki as a means to talk about software development. See http://C2.Com/cgi/wiki?RuleOfThree – Jörg W Mittag May 08 '13 at 09:37
  • 2
    If there's 2 scenarios for reuse, you can branch the logic easily (if, else). Once it gets to three possible paths it becomes easier to re-factor than replicate and maintain. – Andrew Lewis May 08 '13 at 17:22
  • possible duplicate of [Rule of thumb for cost vs. savings for code re-use](http://programmers.stackexchange.com/questions/127118/rule-of-thumb-for-cost-vs-savings-for-code-re-use) – gnat May 13 '13 at 23:55
  • I think it's a convenient excuse for copy-paste, when one can actually refactor and generalize. When you get the third case, you can generalize more. – Alexey Sep 21 '19 at 20:26

1 Answers1

19

I think this rule of thumb exists because it is easy to get caught into playing "What if..." when designing the code for the first time or after the first duplication. I've encountered severe analysis paralysis in some cases because people started designing functionality that might be needed later. But not needed for the immediate problem at hand.

There is an art for designing/writing only what you need, while keeping the code amenable to future re-factoring.

EdH
  • 441
  • 2
  • 4
  • 8
    That's a good point. In my experience, having a third copy also makes the commonalities and differences between them a bit sharper than with only two. – Daniel B May 08 '13 at 07:03