Skip to content
Surf Wiki
Save to docs
general/computer-programming-folklore

From Surf Wiki (app.surf) — the open knowledge base

Rule of three (computer programming)

Refactoring rule of thumb


Refactoring rule of thumb

Rule of three ("Three strikes and you refactor") 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 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 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 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.

References

References

  1. Martin Fowler. (1999). "Refactoring: Improving the Design of Existing Code". Addison-Wesley Professional.
  2. [[Sandi Metz]], [https://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction ''"The Wrong Abstraction"'' (2016)]
Info: Wikipedia Source

This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page.

Want to explore this topic further?

Ask Mako anything about Rule of three (computer programming) — get instant answers, deeper analysis, and related topics.

Research with Mako

Free with your Surf account

Content sourced from Wikipedia, available under CC BY-SA 4.0.

This content may have been generated or modified by AI. CloudSurf Software LLC is not responsible for the accuracy, completeness, or reliability of AI-generated content. Always verify important information from primary sources.

Report