Rule of three (''"Three strikes and you refactor"'') is a
code refactoring
In computer programming and software design, code refactoring is the process of restructuring existing source code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structure, ...
rule of thumb
In English language, English, the phrase ''rule of thumb'' refers to an approximate method for doing something, based on practical experience rather than theory. This usage of the phrase can be traced back to the 17th century and has been associat ...
to decide when similar pieces of code should be refactored to avoid duplication. It states that two instances of similar code do not 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'' and attributed to Don Roberts.
Duplication
Duplication, duplicate, and duplicator may refer to:
Biology and genetics
* Gene duplication, a process which can result in free mutation
* Chromosomal duplication, which can cause Bloom and Rett syndrome
* Polyploidy, a phenomenon also known ...
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
[ Sandi Metz]
''"The Wrong Abstraction"'' (2016)
/ref> and will eventually need to be refactored again.
The rule implies that the cost of maintenance 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.
See also
* Copy-and-paste programming
Copy-and-paste programming, sometimes referred to as just pasting, is the production of highly repetitive computer programming code, as produced by copy and paste operations. It is primarily a pejorative term; those who use the term are often impl ...
* Don't repeat yourself
"Don't repeat yourself" (DRY) is a principle of software development aimed at reducing repetition of information which is likely to change, replacing it with abstractions that are less likely to change, or using data normalization which avoids r ...
(DRY)
* You aren't gonna need it
"You aren't gonna need it" (YAGNI) is a principle which arose from extreme programming (XP) that states a programmer should not add functionality until deemed necessary. Other forms of the phrase include "You aren't going to need it" (YAGTNI) and ...
References
{{reflist
Computer programming folklore
Programming principles