Jump to content

Rule of three (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Dmis09 (talk | contribs) at 16:07, 16 July 2014 (Ugtarmas Corollary -- original research). 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 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[1] and attributed to Don Roberts.

Duplication in programming is a bad practice because it makes the code harder to maintain. Triplication is worse because it makes it harder yet. 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. If the code exists in only one place, then it can be easily changed there. This rule is typically only applied to a small number of lines of code, or even single lines of code [citation needed]. For example, if a program calls a function, and then calls it again when it fails, it is acceptable to have two call sites; however, if it is to be called five times before giving up, there should only be one call site inside a loop.

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

See also

References

  1. ^ Refactoring: Improving the Design of Existing Code, by Mark Viczon Mendoza (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.