Contents |
Refactoring is the process of improving the design of code, without affecting its external behavior. We refactor so that our code is kept as simple as possible, ready for any change that comes along.
The first step in refactoring is to create unit tests that verify the basic functionality. If you're doing XP, with incremental, test-first programming, those tests exist already as a by-product of that process.
Martin Fowler and Kent Beck use the metaphor of "code smells" to describe what you sense when you look at code. Code smells tend to be things that don't indicate that something is necessarily wrong, but they're a "bad sign". You may have heard a similar idea described as "anti-patterns" or "Spidey-sense".
Some smells are obvious right away; you may not detect others until you’re in the middle of refactoring. Look at the original code above, and see what problems you can identify. (Don't restrict yourself to this list!)
Work in an environment that lets you alternate testing and changing your code. Apply one refactoring, then run the unit tests. Repeat this process until your code expresses its intent clearly, simply, and without duplication. At first, it may feel awkward to run the tests so often, but it will speed you up to do so. It takes a few seconds to run the tests, but it reassures you that several minutes worth of changes are OK.
When the code:
These goals are in priority order: if duplication is required to communicate, then the code is duplicated. They are often described as "once and only once". "once" to work; "only once" to avoid duplication.