Refactoring Legacy Code: Where Should I Start?
I've inherited a 5-year-old internal service, and there isn't a single line of test code. Every time I add a feature, things break all over the place, and it's really stressful.
I'm planning to start by adding tests, but before that, I want to clean up the structure a bit. The problem is I have no idea where to start.
For those with experience, what order do you usually proceed in?
9 answers
The right move is to add tests first. Facts.
I also inherited a legacy system as a 5th-year dev and have been struggling with it for a year and a half... The real order isn't 'add tests → clean up structure,' but 'decide what to keep alive → test only that.' If you try to fix everything, you'll be frustrated 100% of the time. The method I used was digging through request logs and first extracting how many times things are actually called. Surprisingly, unused code made up about 30%. If you delete that first, the refactoring scope shrinks dramatically.
Well, isn't that mindset of 'let's sort out the structure first' the most dangerous trap? If you touch the structure without tests, you're breaking things even more while not knowing where it'll blow up. Structural improvements should come after you've laid down the safety net of tests.