Rule of three (computer programming)

For the C++ principle, see Rule of three (C++ programming).

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. However, code refactoring to eliminate duplication also takes time, which might be better spent on other tasks. Triplication has an even higher cost because it makes maintenance 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. The rule proposes that the cost of maintenance certainly outweighs the cost of refactoring when there are three copies, and may or may not if there are 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.

External links

This article is issued from Wikipedia - version of the Monday, January 18, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.