Federico Cargnelutti / Wiki

Refactoring

From Federico Cargnelutti

Jump to: navigation, search

Contents

What is refactoring?

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.

What do you need for refactoring?

  • The original code.
  • Unit tests.
  • A way to identify things to improve.
  • A catalogue of refactorings to apply.
  • A process to guide you.

Unit Tests

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.

Code Smells

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".

What potential danger signs might you see in code?

  • Classes that are too long
  • Methods that are too long
  • Switch statements (instead of inheritance)
  • "Struct" classes (getters and setters but not much functionality)
  • Duplicate code
  • Almost (but not quite) duplicate code
  • Over-dependence on primitive types (instead of introducing a more domain-specific type)
  • Useless (or wrong!) comments
  • Many more...

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!)

Process

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 are we done?

When the code:

  1. Passes its tests (works).
  2. Communicates everything it needs to.
  3. Has no duplication.
  4. Has as few classes and methods as possible.

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.

Personal tools