Recently, I had the opportunity to work on legacy code with several teams from various organizations. I would like to share my experience. We usually start by choosing a piece of code that is “painful”: changing frequently and “scary” to touch because of its complexity. We explain that our purpose is to make the code simpler, readable and easy to change. Establishing the motivation for what we do is important! In essence, the steps we take are:
- Use extract method/rename to make the code more readable (specifically applicable for very long methods).
- Write and execute the first unit test (that’s usually the toughest part) as described by Michael Feathers.
- Add more unit tests until the area you want to refactor is satisfactorily covered.
- Refactor to make the code more maintainable (working in very small steps, as described by Joshua Kerievsky).
- Make the required change using TDD.