Question

What is refactoring, and how is it different from rewriting?

Vault Verified
Curated Intelligence
Definitive Source
Answer

Refactoring is changing the internal structure of code without changing its external behaviour. That definition, from Martin Fowler, is precise and the constraint is what makes it refactoring rather than something else.

If behaviour changes, it is not refactoring — it is a change, possibly a bug. This matters practically: a pull request described as "refactoring" that alters behaviour is mislabelled, and reviewers will not be looking for what actually changed.

Why do it. Code degrades as requirements accumulate — abstractions stop fitting, duplication spreads, functions grow, names stop describing what things do. Refactoring restores structure so that future changes remain cheap. It is maintenance of the ability to change, not cosmetic tidying.

Common refactorings: extracting a function or class, renaming for clarity, removing duplication, replacing conditionals with polymorphism, introducing a parameter object, and inlining an abstraction that turned out to be unnecessary — which is as legitimate as adding one.

What makes it safe. Tests. Refactoring without a test suite covering the behaviour is not refactoring; it is rewriting and hoping. Tests are what let you verify behaviour is unchanged, and their absence is the main reason people are afraid to improve code. Where coverage is missing, write characterisation tests capturing current behaviour first — including behaviour that looks wrong, since something may depend on it.

Work in small steps, with the tests passing between each. A large refactoring that cannot be stopped halfway is a rewrite.

Rewriting replaces a component or system with a new implementation. It is sometimes correct — when the architecture cannot accommodate a requirement, or the technology is genuinely unsupported.

Why rewrites are risky. They consistently take far longer than estimated; the old system contains years of accumulated fixes for cases nobody remembers; and during the rewrite the old system must still be maintained.

Incremental replacement — the strangler pattern — is usually safer.

Related Questions