Article summary
Very few people enjoy debugging legacy applications.† Here’s one concrete, super-handy tip to make it a quicker, less painful process.
A Typical Problem
Imagine you’re debugging a problem, and after some investigation, you find a function that’s looking highly suspicious. Or, perhaps, that function is responsible for setting an internal state that is causing grief elsewhere, and you want to know who’s calling it.
Sadly, the function is called from multiple places, and you’re not sure which one is the culprit. Winding your way through the code is like tracing through the tightly coupled and intertwined components of a mechanical watch movement.
A Simple Solution
How can you find what you’re looking for? Easy. Throw an exception. It’s like throwing that watch movement at the wall.
Throwing an exception has a number of advantages:
- It’s cheap, quick, and easy.††
- You validate your assumption that this particular function is being called, and you learn quickly if you’re barking up the wrong tree.
- You can review the stack trace.
The exception will generally give you at least a call stack so that you can see how you arrived at this function. It may also hold some additional context that is helpful. And depending upon your environment, you may be able to use an interactive debugger to further explore the exception and context.
I hope this tip, which I learned from Michael Feathers at a birds of a feather session at the Agile 2006 conference, is as helpful for you as it has been for me. Michael’s book, Working Effectively with Legacy Code, is packed full of helpful hints like this. Thanks, Michael!
† For the record, yes, I do know of at least one person who enjoys debugging legacy applications. Especially when it’s a character encoding problem. Yes, you read that right. Character encoding problems. Different strokes for different folks, right?
†† Assuming your language has exceptions, of course. If not, think about other ways you could intentionally crash the application and get some helpful output.