Changing Old Code Safely

Old code has no tests and no one who remembers why. Pin down what it does, change it in small steps, replace it piece by piece, and take out patterns that don't earn their keep.

Updated

Before You Change It

  1. Pin It Down: Tests for Code You Didn't Write (Journeyman): Before changing old code that has no tests, write tests that record what it does today, right or wrong, so any change that alters its behavior shows up at once; these characterization tests pin the code down, surprises included, and the surprises become questions for the people who know the business.
  2. Refactoring Toward a Pattern, One Small Step at a Time (Journeyman): With old code pinned down by tests, you can reshape it toward a pattern in steps so small that each one keeps every test green, running the tests after every step and undoing any step that turns one red; the gym's plan if chain becomes a dictionary of pricing rules, and a new family plan becomes one line.

Replacing It Piece by Piece

  1. Strangler Fig: Replace an Old System One Piece at a Time (Freelancer): When an old system is too tangled to keep fixing and too important to switch off for a rewrite, put a facade in front of it and move one feature at a time behind that facade to new code, with an adapter at the border so the old system's ideas don't leak in, until the old system has nothing left to do.

When a Pattern Hurts

  1. Pattern Fever: When a Pattern Makes Code Worse (Journeyman): A pattern is a fix for a problem, so a pattern with no problem to fix (a factory for a factory, a strategy with one choice, an interface with one class that will never have another) is pure cost: more classes and more jumps for no change made easier; the cure is the simplest thing that works, and the pattern comes back when its problem does.
  2. Anti-Patterns: Mistakes with Names (Journeyman): Teams keep making the same mistakes, as they keep finding the same fixes, and the mistakes have names too: the god object, the golden hammer, copy-paste programming and spaghetti code are anti-patterns, answers that look like they work, cause more trouble than they solve, and have a known better answer.

Exercise: Un-Pattern This

  1. Exercise: Un-Pattern This (Journeyman): Take a corner of Summit Gym's code that a teammate made "flexible" for a future that never came, remove what doesn't earn its keep with every test green, and then add two features (a second gym and each instructor's own schedule) that are easy only once the code is simple.