Analysis of Refactoring
It is usual that existing code needs to be maintained–usually to fix bugs or introduce new features. Sometimes, it is not feasible to do this to large programs without restructuring major parts of the code. The existing rode can also have very low readability and be overly and unnecessarily complex, whereby the task of maintenance becomes impractical and inefficient.
A solution to this problem is refactoring, or “cleaning up,” where the code is altered to make it readable and maintainable. thus fixing bugs or implementing new features becomes easy.
The term “refactoring” is analogous to factorization in mathematics, where (x^2 – 1), for example, can be factored as (x+1)(x-1), whereby a simpler and more straightforward structure is shown.
Just like in mathematics, refactoring in software code will not change the observable behavior of the program, and is not (directly) meant to benefit end users, but only the program maintainers. The semantics of the program should not change.
Most large programs will need bug fixes or additional features to meet evolving demands. Since a lot of programming effort goes to maintaining software, it is a good practice to keep code easy to read and maintain.
Refactoring is usually best done if fixing bugs or implementing new features will require ugly, out-of-place hacks. Refactoring will make the design better from a programmer’s perspective. The design is made more flexible and reusable, perhaps even modularized.
Some of the more compelling reasons to refactor are: code duplication, classes that are too large (in object oriented programming) or methods that are too long, or simply when there are too many comments that are necessary to explain what is going on.
It must be ensured that the observable behavior of the program will not change. For example, a very simple refactoring step could be changing a variable name to make its purpose clearer, e.g. changing a variable or method name, as in “i” to “increment,” or turning an if block into a subroutine. Refactoring, also includes removing dead code. Tests should be run every time a significant portion of a code is refactored, to ensure that no errors have been introduced.
Properly refactored code should generally need very little comments, or none at all, since the code should be self-explaining.
Analysis of Refactoring