The code works and the tests are green, but it is getting harder to understand: functions have grown, duplication has piled up, and names no longer match reality. Refactoring is a way to tidy such code in small steps, each of which leaves the program’s behaviour unchanged.
The key rule: behaviour does not change
After every refactoring step the program does exactly what it did before: the same inputs give the same outputs, and errors occur in the same places. That is why refactoring is done in small portions, such as renaming a variable, extracting a function or moving a method to another class, and after each one you check that everything still works. Without tests or fast compile checks you are working blind: you cannot tell “I renamed it and broke nothing” from “I broke it”.
Common techniques
| Technique | What it does |
|---|---|
| Extract function | a piece of code gets a name and becomes a function call |
| Rename | a variable or function name explains its meaning |
| Extract variable | a complex expression gets a clear name |
| Replace magic number | an unexplained number becomes a named constant |
| Move function | a function moves to the module or class that holds its data |
| Extract class | a class with two responsibilities is split into two |
# before: a magic number and an unnamed expression if (now - created).days > 30: archive(order) # after: the same actions, the meaning is clear from the names if days_since(created) > GRACE_PERIOD_DAYS: archive(order) A catalogue of such techniques, with each one explained, is the core of Martin Fowler’s book “Refactoring”: the first edition came out in 1999 with examples in Java, the second in 2018 with examples in JavaScript. The term is older than the book: in 1992 William Opdyke defended a dissertation on refactoring object-oriented programs, but it was Fowler’s book that made the term popular.
When to do it and when not to
- Before adding a new feature: first make the code easy to work with for it, then write the new logic.
- During code review and bug fixes, following the “leave the campsite cleaner than you found it” rule: a small improvement to the places you touch is a normal part of any change.
- Do not mix it with behaviour changes: refactoring and a new feature do not go into one commit, otherwise review cannot tell one from the other.
- Rewriting a module from scratch or replacing a library is not refactoring: if external behaviour or the interface changes, it is a different kind of change with its own risks.
Sources
the term is written from these pagesVerified 9 Nov