Program 02 · Module 04 of 9
Module 04: Characterization Tests and Safe Refactoring
Pin down what code does today before you improve its structure. You write characterisation tests, find seams, and make small refactorings that you can verify and reverse.
- Suggested study time
- 6–8 hours
- Prerequisites
- Modules 1 to 3.; Working knowledge of a test framework for your language.
Sign in to track your progress. Every lesson stays free to read without an account.
Learning outcomes
By the end of this module you will be able to:
- Write characterisation tests that record current behaviour, including its oddities.
- Find seams for isolating code that is hard to test.
- Apply small refactorings, running tests after each step.
- Use an assistant to propose tests and refactorings, and review both for changed behaviour.
Lessons
- 4.1
What Characterization Tests Are
Record what the code does today, so that later changes can be compared with a known behaviour.
40 min - 4.2
Finding Seams in Legacy Code
Isolate hard-to-test code with minimal edits so that tests can observe it.
45 min - 4.3
Golden Master and Approval Tests
Capture complex output once and detect any change to it.
40 min - 4.4
Small, Reversible Refactorings
Change structure in steps small enough to verify and to undo.
45 min - 4.5
Reviewing AI-Proposed Refactorings
Check that an assistant's restructuring preserves behaviour.
40 min
About 3 h 30 min of lessons in total.
Practical assignment
Refactor under test
Choose an untested function with real logic. Pin its behaviour, then improve its structure without changing what it does.
Deliverables
- Characterisation tests covering normal, edge and surprising cases.
- A commit sequence in which each step is a single refactoring with tests passing.
- A note of any behaviour you found odd and left unchanged, and why.
- A before-and-after comparison of the code's structure.
Validation checklist
Use this to check your assignment before you move on.
Knowledge check
Show the answer and explanation
Answer: B. Callers may depend on the behaviour, and mixing fixes with refactoring makes failures impossible to interpret. Fixing inline is tempting. Deleting the test hides what the system does.
Show the answer and explanation
Answer: A. Tests that cannot fail prove nothing. You can check this by changing the code and seeing whether the tests notice. Passing is not the same as protecting.
Show the answer and explanation
Answer: A. Reversibility comes from size and isolation in version control. Approval and the source of an idea do not affect whether a change can be undone cleanly.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.