What I Learned While Refactoring 5-Year-Old Legacy Code
I took over one of our internal services, and it was code whose original author had left the company 3 years ago. There were hardly any comments, let alone tests, and some files were over 2,000 lines long.
For the first two weeks, I just read. Whenever I hit something I didn't understand, I wrote it down in Notion without exception, and that later became my refactoring plan.
The order that actually helped was this:
1. Pin down the behavior with tests first. Before refactoring, locking the current behavior into tests was the most important thing.
2. Tear it apart one function at a time. I tried to change the big structure all at once and rolled back twice.
3. Renaming comes last. Surprisingly, if you start with variable names, the review goes off the rails.
4. Deploy small and often. If you push a big change all at once and something goes wrong, finding the cause is hell.
It took 3 months, and now it's at least code that's readable. Still, I can't shake the thought that if even a few tests had been laid down from the start, it would have been much faster.