Jump to content

Rule of three (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Markbassett (talk | contribs) at 23:28, 17 December 2018 (No knowledge duplication: put citation needed on apparent OR). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Rule of three ("Three strikes and you refactor") is a code refactoring rule of thumb to decide when similar pieces of code should be refactored to avoid duplication. It states that two instances of similar code don't require refactoring, but when similar code is used three times, it should be extracted into a new procedure. The rule was popularised by Martin Fowler in Refactoring[1] and attributed to Don Roberts.

Duplication is considered a bad practice in programming because it makes the code harder to maintain. When the rule encoded in a replicated piece of code changes, whoever maintains the code will have to change it in all places correctly.

However, choosing an appropriate design to avoid duplication might benefit from more examples to see patterns in. Attempting premature refactoring risks selecting a wrong abstraction, which can result in worse code as new requirements emerge[2] and will eventually need to be refactored again.

The rule implies that the cost of maintenance certainly outweighs the cost of refactoring and potential bad design when there are three copies, and may or may not if there are only two copies.

No knowledge duplication

It's interesting to think about duplicated knowledge, not duplicated lines of code. Two pieces of code could be apparently similar, but have completely different reasons to change, because they represent different pieces of knowledge. Therefore, removing that duplication can muddle the logic and make any future change worse.[citation needed]

When you find two apparently similar pieces of source code, question whether you find a reason to have to change them at the same time.

See also

References

  1. ^ Martin Fowler; Kent Beck; John Brant; William Opdyke; Don Roberts (1999). Refactoring: Improving the Design of Existing Code. Addison-Wesley Professional. ISBN 978-0201485677.
  2. ^ Sandi Metz, "The Wrong Abstraction" (2016)