Listen to this post
“Refactoring” refers to the discipline of improving the design of existing code without changing its behavior. It is usually thought of as a way to deal with old legacy code that is functional but poorly designed and thus hard to work with.
Since TDD focuses on driving new behavior from tests, how would refactoring play a role in a TDD team? In three ways:
- New code, generated to make a failing test pass, can be immediately refactored under the protection of the test. This keeps code from accumulating debt over time.
- Test code, like all code, should adhere to the rules of good design: tests, after all, have to be maintained too. The skills that developers learn to refactor older code can also be used to clean up tests when they are passing but have quality deficits.
- Changing (enhancing or debugging) legacy code can be dangerous because it usually lacks adequate tests. In TDD, the first step is to refactor the code proximate to the proposed change just enough that a high-quality test can be added. Then, code can be enhanced under the protection of that test. This is test-driven change and is part of TDD.
Good refactoring skills help with multiple aspects of TDD. It is worth it to make sure your developers know how to refactor.