When should one consider refactoring?
Ideally, refactoring would be part of a continuing quality improvement process. In other words, refactoring would be seamlessly interwoven with other day-to-day activities of every software developer.
Refactoring may be useful, when a bug has surfaced and the problem needs to be fixed or the code needs to be extended. Refactoring at the same time as maintenance or adding new features, also makes management and developers more likely to allow it, since it will not require an extra phase of testing.
If the developer in charge finds it difficult to understand the code, he/she will (hopefully) ask questions, and begin to document the incomprehensible code. The phrases he/she coins may be a good starting point for the names of new methods or classes.
Often, however, schedule pressures do not permit to implement a clean solution right away. A feature may have to be added in a hurry, a bug patched rather than fixed. In these cases, the code in question should be marked with a FIXME note, in order to be reworked, when time permits. Such circumstances call not for individual refactorings, but for a whole refactoring project. When the time has come to address the accumulated problems, a scan for FIXMEs, TODOs, etc. over the code base will return all the trouble spots for review. They can then be refactored according to priority.
What are the benefits of refactoring?
Carrying out a few refactoring operations before or during code debugging may have immediate benefits. Often it becomes easier to spot the bug location. So time is saved, while at the same time the quality of the code is enhanced. Well-structured code is also less error-prone when it comes to extending it.
Kent Beck [Fowler, p.60] states that refactoring adds to the value of any program that has at least one of the following shortcomings:
* Programs that are hard to read are hard to modify.
* Programs that have duplicate logic are hard to modify
* Programs that require additional behaviour that requires you to change running code are hard to modify.
* Programs with complex conditional logic are hard to modify.
Summarising, while sometimes there are immediate benefits to be reaped from refactoring, the real benefits normally come in the long term. They consist in substantially reduced time that developers spend on debugging and maintenance work, as well as in improved extensibility and robustness of the code. In addition, code duplication is reduced, and code re-use fostered. Overall maintenance and development cost should come down, and the speed of the team to react to changing needs should improve.