Code Refactoring

Refactoring is one of the best practices of Extreme programming. Even the most stable project requires occasional modification. The idea is to correct duplication and smelly code. The principle of software entropy suggests that program starts off in a well-designed state, but as new bits of functionality are tacked on, programs gradually lose their structure.
We write a small program that does a specific job well. Later we add new functionality on top of existing program, often in a way that the existing program was not intended to support. In such cases we can either do a complete redesign or patch some work around. Redesign and rewriting existing code results in extra work, which in most cases we can’t afford. Also we may miss existing functionality or introduce new bugs. The principle usually followed is: “If it ain’t broke, don’t fix it!”

Refactoring is somewhere in middle of redesigning the complete code, and leaving the unmanageable and stinking code as it is.

The major factor, which triggers the need for Refactoring, is the request for new feature. Refactoring also helps in keeping the code clean for any newcomer to understand.

Guidelines of Refactoring:

Do not refactor just for namesake. It must be driven by feature request or certain guidelines such as the maximum number of lines proposed for any method or class.
Do not mix refactoring and enhancements. Impose a clear separation with intermediate QA cycles in between.
Take short deliberate steps. Move fields or methods from one class to another. Fuse two similar methods to common method or to the super class. Test after each step.
Make sure we have good tests in place. Ideally refactoring should be backed by automated tests. The cost of refactoring is more affordable at the early iterations of QA.

Reference:
Refactoring- improving the design of existing Program, Martin Fowler. (Addison Wesley)
Java Tools for Extreme Programming, Richard Hightower, Nicholas Lesiecki. (Wiley Comp Publ.)