Code Re-Factoring

What is Code Re-Factoring?

Code re-factoring is simply improving the design of existing code by changing it to simplify and improve it.

Why use Code Re-Factoring?

For short-term or projects where requirements are static, having to re-factor code fundamentally means you failed to appropriately design the code in the first place. It also fundamentally means there will be project delays and possibly unexpected effects of changing the underlying design.
However, for an Agile project or a project maintaining Legacy code, re-factoring is an integral part of the software development process. If code is difficult to work with and modify and it is NOT re-factored, maintenance and quality assurance costs will skyrocket for future changes. Hence, re-factoring is vital to keeping maintenance costs reasonable for maintenance of long-lasting legacy codes. 
Also as a software application ages, the technology used for the original design becomes out of date or worse yet, no longer supported. This forces you to re-factor the code to replace the old libraries or method calls with ones that are supported by the vendor. Even if everything is working correctly you may have to re-factor or even re-write the code because the language becomes so out of date that no one on your team knows how to maintain it.

How to Re-Factor Code?

The first requirement before you should re-factor code is to have a good regression testing system, automated if possible, that tests all required features of the software. This should test the system at all levels: unit, component, and system. Once, this is in place, after making changes you can re-run these tests to verify that the re-factored code still exhibits the right behavior. 
The second requirement is that re-factoring changes should be reviewed by other developers before they are implemented. You need to hold a code review, see Code reviews before implementing the changes to make sure the entire team is aware and approves of what is changing.
The third requirement is that if possible, re-factoring changes should be done in small steps rather than in one fell swoop. Figuring out how to phase in the re-factoring changes can be as important as the re-factoring changes themselves. If you re-factor in a small step and your automated test system detects problems, it will be easy to find the problem and fix it. If you change a large amount of code during your re-factor and a problem is found, it is very difficult to debug all the problems that were introduced and return to a stable code base.
Further Reading.
Martin Fowler's Refactoring