Hit with a Reality Check While Refactoring Legacy Code
I took on refactoring a service that's been running for 10 years without a single test, and honestly, the more I touch it, the more it feels like it's going off the rails.
If I fix one function, I don't know where something will blow up, so every deployment makes my heart race. But if I don't fix it, I can't add new features.
How do senior devs handle this kind of situation? Is the answer just to gradually tear it apart and fix it bit by bit?
5 answers
Incremental is the right answer, but you shouldn't take "incremental" too optimistically. At first, whenever I added a feature, I'd just clean up a little around it. But even that needs justification when your boss asks, "Why are you spending time on refactoring?" So I quietly slipped "includes cleanup of existing modules" into the spec for new features. Just something to keep in mind.
Agreed... Legacy code without tests is a real minefield lol
Well, that's kind of... the seniors all just let it keep running lol. I don't think perfect refactoring exists.
If a service has been running for 10 years, all kinds of edge cases and business rules are already baked into the code. If you try to rewrite it from scratch, it will fail 100% of the time. The approach I used was: 1) lay down characterization tests around the function you're about to touch first, 2) capture actual behavior with logs/metrics before and after deployment and use that as your baseline, and 3) never mix refactoring with feature changes. If you stick to this, you'll move slower, but you'll have far fewer heart-in-your-throat moments.
Got a source? I'm curious about the specifics of how to run the trait test.