DEV Community

Cover image for Rule of three
James Wade
James Wade

Posted on • Edited on

5 1

Rule of three

Sometimes called “1, 2, refactor”, the “rule of three” is 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.

“Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior”
― Martin Fowler

This is a rule that has really served me well in recent years when I’ve come up against challenges on when something should be refactored.

As developers it’s all too easy to spend too much time trying to engineer perfection, when really, all we needed to do was what was asked of us.

We also have to recognise that we can’t always plan for the future and by refactoring or abstracting code too early, you may find that you back yourself into a corner which results in, you guessed it, two versions of the code, each with slight differences to accommodate the tight coupling.

It really only makes sense to defer the decision to refactor once you know a bit more about what it is you’re trying to do.

After all, you can’t plan for what you don’t know. You can only deal with the information that you have right now, so we should programme for that.

“Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent.”
― Martin Fowler

This is, being a rule of thumb means that there are exceptions to this rule, there are good times to refactor as well as bad. This rule prevents you refactoring before you have enough information.

If you find yourself in a situation where you’re asking whether it’s too early to refactor, it probably makes sense to apply this rule.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more