In my experience, most programmers hardly spend any time refactoring their code. Even the simplest of refactorings to do, rename field/variable/method and extract method, are not done more often than they should be. Sure, it's nice to see that more and more programmers are writing
unit tests but the way they write them still misses the point. And to write unit tests without paying attention to refactoring to me is just asking for more trouble.
So here are some things from the book that I'd like to highlight about refactoring:
The Pragmatic Programmer wrote:
When Should You Refactor?
When you come across a stumbling block because the code doesn't quite fit anymore, or you notice two things that should really be merged, or anything else at all strikes you as being "wrong," don't hesitate to change it. There's no time like the present. Any number of things may cause code to qualify for refactoring:
Duplication You've discovered a violation of the DRY principle (Don't Repeat Yourself)Nonorthogonal design. You've discovered some code or design that could be made more orthogonalOutdated knowledge. Things change, requirements drift, and your knowledge of the problem increases. Code needs to keep up.[/b]Performance. You need to move functionality from one area of the system to another to improve performance.
If I had to add one thing, I would add this:
Lack of Clarity. If you or anyone else has to spend five minutes trying to understand what a method does, then you need to change something so that the code's intent is immediately obvious.
These days there are people, in particular I imagine Michael Feathers among others, who would argue that the last point about performance is not really a motivation for refactoring. Refactoring and optimization may appear to do the same kind of things but their goals are different. Refactoring is about changing structure to improve maintainability. Optimization is about changing structure to improve resource usage. One thing I found from interviewing people is that many think that refactoring is mainly about optimization. Since PP was published in 2000 and Michael Feathers' book "Working Effectively with Legacy Code" where he differentiates refactoring from optimization was published in 2005, I'll give the PP guys a pass on this one.
