What I Learned While Refactoring Legacy Code for 3 Months

The first thing I was assigned after joining the company was an eight-year-old monolithic service. There were no tests, the comments were all just names of past maintainers, and it took 20 minutes just to build. My team lead said, "It works for now—don't touch it," but I could tell that if we kept adding features in that state, we'd be in real trouble.

For the first month, I did nothing but read code. Where the flow starts, why this function looks the way it does, why this module is called through five other modules before it gets invoked. It can feel like a waste of time, but if you skip this and start touching things right away, you'll create debt you absolutely have to pay back.

Starting in the second month, I added tests first. I wrote tests that pinned down the current behavior before changing any functionality. The key here was "even strange behavior gets recorded in tests exactly as it is." If you inadvertently fix something that originally behaved that way, it can blow up somewhere else.

In the third month I started refactoring, and I followed only two principles.

  • Change only one thing at a time: If you change the structure, don't touch the logic; if you change the logic, leave the structure as it is.
  • Commit small, deploy often: Ten small PRs are easier to review and roll back than one huge PR.

As a result, build time dropped from 20 minutes to 4 minutes, and most importantly, I no longer felt afraid when adding features. Performance didn't improve dramatically, but that wasn't the goal anyway.

Looking back, what helped most was the perspective that "refactoring isn't about making code pretty; it's about making changes safe." If you're in the same situation, I recommend starting with tests.

by 데이터덕후552

10 answers

This is so true lol Especially, reading only code for the first month is really important, but everyone skips it because they think it’s a waste of time

by 스타트업러306 · ▲0

Just getting an 8-year-old monolith into a workable state in three months is impressive in itself. In a similar situation, our team kept telling ourselves "it works for now," and two years later we ended up rewriting the whole thing. If we'd at least had tests back then, we would have saved at least six months.

by 호기심천국316 · ▲0