Jump to content

Rule of three (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Asqueella (talk | contribs) at 23:38, 8 August 2018 (Fowler talks about similar, not duplicate code, and doesn't go into much detail about the rationale (so "proposes"->"implies"). Plus minor changes to wording.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Rule of three 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. This process is error-prone and often leads to problems. Triplication has an even higher cost because it makes maintenance harder yet. If the code exists in only one place, then it can be easily changed there.

However, refactoring code to eliminate duplication takes time, which might be better spent on other tasks. Additionally, choosing a good design to refactor code into becomes easier when there are more examples of duplicated code to see patterns in. With three examples of similar code, it is easier than with two examples to see what parts of the code should be abstracted and what parts should be the same in all cases.

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.

As Charles Petzold puts it, "Three or more? Use a for!"[2] [3]

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. ^ "Does Visual Studio Rot the Mind?". Charlespetzold.com. Retrieved 2013-07-08.
  3. ^ "Site Class [AX 2012]". Msdn.microsoft.com. Retrieved 2013-07-08.