CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

Refactoring

Behaviour stays, structure improves.

Refactoring means changing the structure of code without changing what it does. It only works if there is a way to check that behaviour stayed the same. That way is a set of tests (module 5).

The method in small steps:

  1. Write tests that pin down the current behaviour, even when that behaviour is odd. In the example, the four orders and their prices serve as the tests. These are sometimes called characterization tests.
  2. Make one small change, such as extracting a constant or a method.
  3. Run the tests. If they pass, continue. If not, undo the step.
  4. Repeat. Commit often.

CC chapter 14 describes the same rhythm: improve in many tiny steps and keep the tests passing after each one, and do not start a big rewrite that leaves the code broken for days. Large rewrites are risky because failures cannot be traced to a single step.

Some common smells from CC chapter 17, with their usual cures:

Smell What it looks like Usual cure
Duplication The same logic in two places Extract a method or class (DRY, Level 2)
Type switch A switch on a type code, repeated Interface with one class per case
Magic number A raw number whose meaning is unclear A named constant
Feature envy A method that mostly uses another object's data Move the method to that object
Dead code Code that is never run Delete it
Too much information A class with a wide public surface Narrow it, hide what callers do not need

Feature envy deserves an example. CC shows a pay calculator that reads many details of an employee through getters and does the sums itself. The method envies the employee class. If most of its lines use the employee's data, the method belongs in the employee class, which is the idea of cohesion in Level 2, module 6.

Refactoring is also not endless. Stop when the code is clear and the next change is easy. Clean code that is never changed again did not need the extra work.

Refactoring

Refactoring is changing the inside of code to make it clearer or easier to extend, while its visible behaviour stays exactly the same.

Example: replacing the type switch with a list of rules, with the four prices unchanged.

Common mistake

Refactoring with no tests, or mixing a refactoring with a new feature in one step. If something breaks, it is unclear which change caused it. Do the cleanup first, check, then add the feature.

Check yourself: 1. What must exist before you refactor? 2. What does a characterization test pin down? 3. Where should a method with feature envy go?