I’ve recently been working on adding a new feature that, for many reasons, requires a great deal of refactoring to our existing codebase.
I’ve done code refactoring for most of my career, and I’ll do it many more times until the day I retire. When I started, though, things were a bit different from what they are now. I didn’t know about the concept of unit testing, and the companies I worked for were not interested in or didn’t know about this concept either. As a result, I relied on manual verification tests to confirm that everything was fine. Many times they were not, and I would just find my bugs when they were already in production.
The introduction of automated testing, particularly unit and integration tests, was a game changer. Many time, when I write a new feature, it takes me way more time to write automated tests than to write the actual code for the feature! But despite this, I keep writing them every time because I know how useful they are.
When we already have automated tests for a feature, doing a refactor is usually as simple as just changing the code, and running the tests. That only works if we already have a good test coverage though.
The area that I am touching has an uneven test coverage, so, before refactoring the code, I need to write the missing tests so I can validate how the feature works. A few times I have even found bugs in production code by doing this. Only once I have improved the test coverage I move to changing the code.
It’s important to remember that automated tests are not perfect. They cannot test every scenario, and we’ll likely forget to add some (I’ve been guilty of this a few times during this refactor). As Dijkstra said [1]:
Program testing can be used to show the presence of bugs, but never to show their absence!
But even considering that, aiming for a high coverage that follows a good test design gives us way more confidence than having no tests at all.
Happy coding!
José Miguel
Share if you find this content useful, and Follow me on LinkedIn to be notified of new articles.
[1] Notes on Structured Programming, Prof. dr. Edsger W. Dijkstra

