/working-effectively-with-legacy-code:scratch-refactoring-for-code-understandingfrom working-effectively-with-legacy-code
Guides throwaway refactoring to understand unfamiliar legacy code by restructuring freely, producing learning notes, then discarding changes. Use when code is too complex to change safely.
Ships in working-effectively-with-legacy-code. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Use this skill when a developer cannot understand a section of code well enough to change it safely. Scratch refactoring is the right tool when:
Scratch refactoring is a comprehension technique, not a production technique. It is a complement to characterization tests (which pin down behavior) and effect sketches (which map change propagation). When you need to understand structure before you can even write a characterization test, scratch refactoring is the right first step.
Do not use this skill if:
Before starting, collect:
If the developer cannot state a learning goal, use this default: "Identify the top-level responsibilities of this code and the relationships between them."
Create a scratch branch (preferred) or confirm a clean stash before touching any file.
git checkout -b scratch/understand-<target-name>
# or, if branch creation is not practical:
git stash push -m "scratch: pre-exploration state"
Why: The discard step (Step 5) only works cleanly if the scratch branch can be deleted or the stash popped. Without this isolation, exploratory changes can accidentally survive into production code. The version-control system is the safety net — it must be set up before the exploration begins, not after.
Read the target code with fresh eyes. Scan for:
Restate the learning goal as a concrete question. Write it down — this becomes the first line of your learning notes.
Why: Without a stated goal, scratch sessions drift. The goal acts as a stopping condition: once you can answer the question, the session is done. This prevents over-investment in the scratch structure.
Refactor the target code without writing any tests. Common moves:
Do not stop to make the code production-ready. Do not worry about performance, test coverage, or code review standards. The goal is visibility, not correctness.
Why: The normal constraint "do not refactor without tests" exists to prevent regressions in production code. In a scratch exploration that will be discarded, that constraint does not apply. Removing it allows rapid structural manipulation that would otherwise require a full seam-introduction and characterization-test cycle. The speed is the point.
As understanding emerges — not at the end, but during the session — write down what you are learning. Do not capture the refactored structure. Capture the insights.
Learning notes template (save as learning-notes.md in a scratch location):
# Learning Notes: <target code>
Date: <today>
Question: <the learning goal from Step 2>
## Structure discovered
<plain-English description of the top-level structure: phases, responsibilities, collaborators>
## Surprises
<things that were unexpected or counterintuitive>
<any false assumptions that were corrected during the session>
## Dependencies and risks
<anything that propagates changes widely, or that the code depends on unexpectedly>
## Next-step recommendation
<what the developer should do next: write characterization tests for X, apply technique Y, investigate Z>
Why: The learning notes are the deliverable, not the refactored code. If you write down what you learned but discard the scratch code, you have everything you need. If you keep the scratch code but write nothing down, you have a dangerous artifact and no portable insight.
Delete the scratch branch or pop the stash back to the pre-exploration state.
# If you used a scratch branch:
git checkout main # or your base branch
git branch -D scratch/understand-<target-name>
# If you used stash:
git checkout -- .
git stash pop
Verify the working tree is clean before moving to production work.
Why: Feathers is explicit: "Throw that code away." The scratch structure was shaped by the order of your discoveries, not by production design intent. Committing it introduces structure that was never evaluated against the full system, may contain mistakes made during rapid exploration, and — most insidiously — biases future refactoring by making one particular decomposition feel "already done." The insight belongs to the developer's head and the learning notes. The code belongs in the trash.
| Input | Required | Description |
|---|---|---|
| Target code path | Yes | File(s) and class/method to understand |
| Learning goal | Yes | The specific question to answer (elicit if not provided) |
| VCS clean state | Yes | Clean working tree or scratch branch before starting |
| Current understanding | No | What the developer already knows (prevents redundant exploration) |
| Output | Format | Kept or Discarded? |
|---|---|---|
| Learning notes | learning-notes.md | Kept — the primary deliverable |
| Scratch refactored code | Modified source files on scratch branch | Discarded — deleted after session |
Learning notes template (minimum viable):
# Learning Notes: <target>
Date: <YYYY-MM-DD>
Question: <learning goal>
## Structure discovered
<top-level structure in plain English>
## Surprises
<unexpected findings; corrected false assumptions>
## Dependencies and risks
<what propagates changes widely>
## Next-step recommendation
<characterization tests / technique / investigation to do next>
1. Never commit scratch refactoring — VCS is the safety net, not the deliverable. The version-control system exists so that the scratch branch can be deleted cleanly. Committing exploratory code introduces structure that was shaped by the order of discovery, not by production design intent. The branch is a workspace, not a feature branch.
2. A scratch mistake can create a false mental model — verify conclusions against the original code. When you refactor freely, you will sometimes make extraction mistakes: a method name that implies the wrong abstraction, a grouping that hides a real coupling. If you trust the scratch structure without checking it against the original, you may carry a wrong understanding into production work. Before writing learning notes, cross-check surprising conclusions against the unmodified code (easy to do since the original is one branch switch away).
3. Attachment to scratch structure biases real refactoring — keep the insight, not the shape. A scratch session that ends with "I did the refactoring already, let me just commit it" has failed. The scratch decomposition may be one valid decomposition — but it was found under comprehension pressure, without the full context of the change goal, tests, and system design. Real refactoring, done with tests and full context, will often find a better structure. The learning notes preserve what matters; discarding the code preserves the developer's ability to see that better structure.
A developer needs to modify a 300-line calculateInvoice() method but cannot determine which lines handle tax calculation versus line-item accumulation versus discount application.
Scratch session:
scratch/understand-calculate-invoice.accumulateLineItems(), applyVolumeDiscounts(), calculateTaxByJurisdiction(), formatInvoiceOutput().Result: The developer now knows exactly where to add the new billing adjustment — in the accumulation phase, before discounts — and what tests to write first (a characterization test for the government-account discount case).
A team inheriting a CustomerManager class (800 lines, no tests) cannot determine what it owns versus what it delegates.
Scratch session:
scratch/understand-customer-manager.subscription sub-object — extract a SubscriptionHandler conceptually in the scratch.Result: The team's real refactoring plan is now grounded: introduce a SubscriptionHandler class with characterization tests, extracted from CustomerManager using the Extract Class technique. The scratch session revealed the seam without committing premature structure.
This skill is licensed under CC BY-SA 4.0. Derived from Working Effectively with Legacy Code by Michael C. Feathers (2004), Prentice Hall. Attribution required on redistribution.
legacy-code-change-algorithm — the six-step master procedure that scratch refactoring feeds into; use this skill first when the code is too opaque to identify change pointschange-effect-analysis — use after scratch refactoring to map propagation of a planned change through the now-understood structurebig-class-responsibility-extraction — the production technique for splitting large classes discovered via scratch refactoringWhat SKILL.md sets; muted values are Claude Code's defaults
16 skills in this plugin
/big-class-responsibility-extractionIdentify and extract responsibilities from an oversized class using Feathers' 7 heuristics + feature sketches. Use whenever a developer faces 'this class is too big', 'god class', 'monster class', '500-line class', 'class with 50+ methods', 'class with too many responsibilities', 'SRP violation', 'hard to test because class does too much', 'team keeps editing same class', 'merge conflicts on one class'. Activates for 'single responsibility', 'extract class', 'class decomposition', 'responsibility split', 'interface segregation', 'class bloat', 'swamp class', 'god object', 'feature sketch', 'class too big'./change-effect-analysisTrace the blast radius of a legacy code change and produce a test placement plan with pinch points. Use whenever a developer needs to decide WHERE to write tests for a pending change — 'what should I test?', 'where to test?', 'how far do the effects propagate?', 'what else could this break?', 'how to find test points', 'pinch point', 'effect sketch', 'impact analysis', 'blast radius', 'interception point', 'high-leverage test'. Triggers for 'I need to make many changes', 'many classes affected', 'cluster of related changes', 'cross-class refactoring'./characterization-test-writingWrite tests that pin down the actual current behavior of untested legacy code as a safety net for change. Use whenever a developer needs to create a regression safety net before modifying code — 'I don't know what tests to write', 'what should I test in legacy code', 'how do I write tests for code I didn't write', 'tests to preserve behavior', 'golden tests', 'snapshot tests for old code', 'characterization test', 'cover before modify'. Activates for 'legacy code testing', 'untested code', 'write tests before changing', 'regression safety net', 'behavior-preservation tests', 'pin down behavior'./dependency-breaking-technique-executorSelect and execute the right dependency-breaking technique from Michael Feathers' catalog of 24 named techniques (Part III of Working Effectively with Legacy Code) for a specific testability obstacle. Use when a class or method cannot be placed under test due to a hard-coded dependency, and you need concrete step-by-step mechanics for breaking it safely — without existing tests protecting you. Activates for 'can't test this class', 'constructor dependency', 'global variable blocking tests', 'static call in method', 'inject a fake', 'break dependency for testing', 'extract interface legacy', 'subclass and override', 'parameterize constructor', 'encapsulate global', 'dependency injection without framework', 'extract and override', 'how to fake this in test', 'legacy code testability refactoring'./duplication-removal-via-extractionRemove duplicated code across methods and classes by extracting small shared utilities first and letting larger structure (superclass, Template Method) emerge. Use whenever a developer says 'I'm changing the same code in multiple places', 'I'm fixing the same bug in 3 files', 'copy-pasted code everywhere', 'duplicate logic', 'DRY violation', 'same code in multiple classes', 'repeated patterns', 'shotgun surgery'. Activates for 'extract method', 'extract class', 'pull up method', 'Template Method pattern', 'superclass for duplication', 'deduplicate', 'shared utility', 'parallel classes'./legacy-code-addition-techniquesAdd new functionality to untested legacy code using Sprout Method, Sprout Class, Wrap Method, or Wrap Class — whichever best fits the dependency profile. Use whenever a developer needs to add a feature, log statement, validation, or any new behavior to legacy code that they can't easily test — 'I have to add this feature fast', 'no time for a big refactor', 'just need to log this', 'add a check to existing method', 'need to add behavior without breaking legacy', 'sprout method', 'sprout class', 'wrap method', 'wrap class', 'decorator for legacy'. Activates for 'quick change to legacy', 'under time pressure', 'can't test this class but need to add a feature', 'extend without editing'.npx claudepluginhub bookforge-ai/bookforge-skills --plugin working-effectively-with-legacy-codeOther plugins' skills for the same job