Concept: Refactoring
Relationships
Related Elements
Main Description

Description

Refactoring is the practice of improving the design of a system without changing its behavior. Refactoring is a critical practice and skill in iterative development. The programmer is either adding a new feature or refactoring. XP programmers consciously choose between refactoring and adding new functionality on a minute-by-minute basis. Some refactorings are trivial, such as renaming or moving things. Other refactorings allow you to exchange procedural logic with polymorphism, and still larger refactorings exist to introduce design patterns.

While processes like Extreme Programming rely on refactoring to let the design emerge, the usefulness of refactoring extends beyond the Agile Methodologies. As feature requests and bug fixes require changes to a system, refactoring techniques allow the programmers to maintain a good design. Refactoring can also be used to improve the design of an existing system.

Refactoring is not new. Developers have been refactoring for years, though only recently have people started to catalog refactorings. Refactoring has become such an important part of development that professional-level Integrated Development Environments (IDEs) either include built-in tools or have plug-ins to provide refactoring support.

If your system isn't being refactored as it is modified, your design deteriorates; methods become longer, classes take on more responsibility, more code gets cut and pasted around your system, previously cut-and-pasted code has to be modified in several places.

If your system becomes brittle and inflexible, your developers will have to spend more time and money to add features or fix bugs. As the design continues to deteriorate, fixing one bug creates two more, or the cost of adding a new feature out weighs the benefit of having it because so much of the system has to be modified. There are many analogies to describe this battle against entropy; from cleaning as you go to design debt.

Knowing the refactorings isn't enough. Developers must be able to identify problem areas of the program design (often referred to as "smells"). These are the places where refactoring can be used to improve the design of the code. Design skill and experience are needed to recognize bad code smells.

Automated tests provide a safety net when making changes. The automated tests report when the functionality of the system changes. Make a structural change to the software; see that the tests still pass. You can confidently refactor.

Where do all these tests come from? In XP, they are developed using Test-Driven Development. It is possible to refactor without tests, but you run the risk of unknowingly introducing bugs or breaking existing functionality.

Benefits

  • Allows the design to emerge over time.
  • Keeps the design from rotting.
  • Reduces cost of change.

Related Information

 See the Refactoring Guidelines.