Refactoring
Improving code structure without changing its behavior.
Refactoring keeps a codebase easy to change. It works best in small steps protected by tests, folded into feature work. Knowing when not to refactor matters too.
Why it matters for a product engineer
Refactoring changes the structure of code without changing what it does. It keeps a codebase easy to change, which is what lets a product keep moving. Done in small steps with tests, it is safe and cheap. Done as a big rewrite, it is one of the riskiest things a team can do.
How to do it
- Refactor when you need to change the code anyway: make the change easy, then make the easy change.
- Make sure tests cover the behaviour first. If they do not, add them.
- Take small steps, and run the tests after each one.
- Keep refactoring and new behaviour in separate commits, so reviews stay clear.
- For critical paths, run the old and the new code side by side in production and compare their results before you switch.
- Remove the old code when you are done. A half-finished migration is worse than either version.
Common mistakes
- A big-bang rewrite with no way back.
- Refactoring without tests.
- Mixing refactoring and features in one change.
- Refactoring code nobody needs to change.
- Leaving two versions of the same logic running for ever.
Example
In 2015, GitHub replaced the code behind the Merge button, one of its most critical paths, with a new merge engine. It used Scientist, its own library: users always got the old result, while the new code ran next to it and every difference was logged. After four days at growing shares of traffic, the new code ran on all requests for 24 hours with no mismatches. Tens of millions of merges were checked, in about five days of part-time work.
One merge during GitHub's Scientist experiment
- 07A bug in the new code cannot reach the user.
The new code was tested on real traffic without any risk to users. The comparison even found a bug in Git itself.
ReportedVicent Martí, 'Move fast and fix things', GitHub blog, Dec 2015
Sources: Move fast and fix things (Vicent Martí, GitHub) ↗ · Refactoring (Martin Fowler) ↗
Resources
2- articleStart here
Technical debt quadrant ↗
Martin Fowler · 2009 · 4 minNot all debt is bad: deliberate and prudent debt is a choice, reckless debt is a mess.
- bookGo deeper · Paid
Refactoring ↗
Martin Fowler · catalogThe standard book on improving code without changing behavior. The site has a free catalog of the refactorings.
Tools
2- ToolOpen source
- ToolOpen source