Arnon Gal-Oz, an absolute rock star of software engineering, cautioned me with regard to the common misconception of refactoring. His point is well taken, especially since the misconception was one I held for a couple of years, before I stumbled upon the correct (and far more useful) definition.
In short, refactoring is not rewriting, nor is it intended to fix bugs or optimize code. Of course it might, as a side affect, but I think it’s far better to entirely ignore those otherwise laudable goals when one refactors.
Refactoring is quite simply imposing good, or even just better, design on existing code. Period. Full stop. End of sentence…it would make a good telegram, wouldn’t it?
For something so simple it’s surprisingly powerful, not to mention cost effective. It can even save on psychiatric bills. Really! :-)
It’s powerful because changes are made using a known methodology in small steps within a framework of continual tests. Since the code worked before you started, and since you will have tests to run at each step, you will know immediately when a change has gone wrong and what is at fault.
It’s cost effective because it makes changing features or behavior easier to implement and since you’ll already have a good test for the refactored code, changes will be easier to test. You really will spend less time debugging new code or new bugs later if you refactor now, even if you don’t have an immediate need to do any new programming right away.
Even better you can start small and convince yourself. You might even be fortunate to work in an environment that has automatic refactoring such as Java. But the benefits still apply to those of us who have do manual refactoring.