Rule of three (programming)
Encyclopedia
Rule of three is a code refactoring rule of thumb
Rule of thumb
A rule of thumb is a principle with broad application that is not intended to be strictly accurate or reliable for every situation. It is an easily learned and easily applied procedure for approximately calculating or recalling some value, or for making some determination...

 to decide when a replicated piece of code should be replaced by a new procedure. It states that you are allowed to copy and paste the code once, but that when the same code is replicated three times, it should be extracted into a new procedure. The rule was introduced by Martin Fowler
Martin Fowler
-Online presentations:* at RailsConf 2006* at JAOO 2006* at QCon London 2007 * at QCon London 2008 * at ThoughtWorks Quarterly Technology Briefing, October 2008...

 in Refactoring and attributed to Don Roberts.

Duplication in programming is a bad practice 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. 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. For example, if you want to call a function, and then call it again when it fails, it's OK to have two call site
Call site
In programming, a call site of a function is a line in the code which calls a function. A call site passes zero or more arguments to the function, and receives zero or more return values.-Example:...

s; however, if you want to try it five times (5 >= 3) before giving up, there should only be one call site inside a loop.

Also as Charles Petzold
Charles Petzold
Charles Petzold is an American programmer and technical author on Microsoft Windows applications. He is also a Microsoft Most Valuable Professional....

 puts it, "Three or more? use a for
For loop
In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement....

!"

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK