Refactoring Legacy Code: Can We Trust Existing Tests?

rweisleder

Roland Weisleder

Posted on March 1, 2024

Refactoring Legacy Code: Can We Trust Existing Tests?

Recently, I saw an interesting question on LinkedIn: "When making a moderately large refactor, should we trust the tests we already have, or should we drive our refactor with new tests?"

As an independent consultant who is bringing legacy systems into the future, of course this question is of great interest to me. First of all, in legacy code, tests do not always exist or the code coverage is not that high. My first step is always to verify the existence of tests and evaluate their coverage. It's important to ensure that all critical areas, especially those that will be refactored, are well covered by tests. If not, then adding or improving tests is essential.

Understanding the tests is as important as having them. If they don't accurately reflect the business requirements, I will then focus on refining them or creating new tests. This approach not only helps to understand the codebase, but also to build confidence in its reliability. In essence, getting to know the code through testing is important to me.

When it comes to the refactoring itself, the goal is to change the structure without changing the business logic. This is where the IDE and automated refactoring tools are invaluable. They're less likely to make mistakes than moving code around by hand.

So, to answer the original question: First, we need to have enough tests we can trust. Trust can be gained by having sufficient knowledge about the code unit to be refactored. This can be done, for example, by writing new tests. Automated tools help us to make the refactoring itself less error-prone.

This post was originally published on LinkedIn. Follow me there for more tips on working with legacy systems.

💖 💪 🙅 🚩
rweisleder
Roland Weisleder

Posted on March 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related