I have a confession to make:
I love clean code.
Almost unreasonably so.
This passion used to get me into trouble when I cleaned up messy code.
Extensive manual testing confirmed that my refactored software was ready for production.
Yet, after deployment, hundreds of users discovered the system would no longer work as expected! Understandably, many were unhappy.
The legacy code I was working with was of the worst kind: So coupled, a code change in one area could produce a bug in an unrelated area. It was like turning on the kitchen lights would set one's bed on fire!
I had broken the application a few times. I was starting to get a reputation as a Bug Farmer. My career was moving in the wrong direction!
Nobody cares about the clean code when the price is production bugs.
Fair enough.
It was time for a change.
Working Effectively with Legacy Code
I had recently read "Working Effectively with Legacy Code" by Michael Feathers. This insightful book is packed with techniques for working safely with messy code.
My Old Process for changing code (bug fix / refactoring / feature):
- Carefully identify where to change the code,
- Make the change
- Manually test the change (myself & tester),
- If all is good, deploy to production,
- Fix new bugs found by unhappy users!
Feathers' book helped me improve my development process.
My New Process:
- Carefully identify where to change the code,
- Identify where to put unit tests covering the intended changes.
- If necessary, break dependencies to make code unit-testable.
- Write the tests,
- Make the changes while keeping the tests green (i.e. passing)
- Deploy to production.
- Done. Happy users!
Changing my process for modifying code made a world of difference to the users' happiness. Defects still happened but less frequently.
My state of mind recovered from an constant anxiety of breaking production to near-relaxation, knowing that the unit tests had my back.
Since then, I have advocated for securing legacy code with unit tests before making changes. I'm proud to say that teams I have worked with who have adopted this innovative, unit tests-first approach have seen fewer defects, less downtime, less time fixing bugs, happier customers, and fewer customer complaints after only a few months of consistently putting tests first!
Conclusion
If you're suffering from the adverse effects of buggy legacy code, I recommend securing the codebase with unit tests before making changes. You'll learn how in future newsletter editions. Or you could read Michael Feathers' book. Good luck! 🍀