/working-effectively-with-legacy-code:duplication-removal-via-extractionfrom working-effectively-with-legacy-code
Removes duplicated code across methods and classes by extracting shared utilities and letting larger structures like superclasses and Template Method emerge. Requires tests before extraction.
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.
You recognize a duplication problem: every time a rule changes, you make the same edit in multiple places. Every bug fix requires the same patch applied three times. Parallel classes drift apart over time because there is no single location of truth. Feathers calls this "I'm Changing the Same Code All Over the Place" — one of the most frustrating symptoms in legacy systems.
The instinct is often to plan a grand restructuring before touching anything. Resist it. Duplication removal does not require a reengineering effort. You can remove it in small, safe steps while doing your regular work, and the larger structure will reveal itself.
Before arriving here, run characterization-test-writing to establish a regression safety net across all the duplicated sites. Every step in this process makes a mechanical change. Without tests, you cannot distinguish "still correct" from "silently broken."
Do not use this skill when the similarity is coincidental — two classes that happen to use the same 3-line sequence but for unrelated reasons. Coupling them creates a false dependency. The test is: if one copy needed to change, would the other need to change too? If yes: real duplication. If no: coincidental similarity.
Collect before starting:
Grep to find all occurrences if the duplication is spread across many files.characterization-test-writing first and return here.Run the test suite. Every class and method containing the duplicated code must be covered by at least one test. The tests do not need to be comprehensive — they need to catch behavior changes in the specific code you are about to move.
If any duplicated site has no test coverage: stop. Invoke characterization-test-writing for the uncovered sites, then return here.
Why tests before extraction: Each mechanical step in this process is safe in isolation but can introduce a subtle error. A miscopied variable name, a typo in the extracted method signature, a wrong access modifier — any of these silently changes behavior. Tests transform "I hope this is still correct" into "I know this is still correct."
Read the duplicated methods. Do not look for the largest region of similarity — look for the smallest repeated sequence that forms a coherent unit. A two-line pair that always appears together is a valid extraction target even if the surrounding method has dozens of lines.
Feathers' heuristic: "Start small. If I can remove tiny pieces of duplication, I do those first because often it makes the big picture clearer."
Write down the fragment verbatim. Give it a candidate name. Ask: does this name describe what the fragment does, not how? If yes, you have found your extraction target.
Example: outputStream.write(field.getBytes()); outputStream.write(0x00); — always paired, always together. Name: writeField(OutputStream, String).
Pick one of the classes containing the duplication. Extract the fragment there first.
Do not touch the other class yet. The goal of this step is a passing, locally-clean change in exactly one class.
// Before (LoginCommand.write):
outputStream.write(userName.getBytes());
outputStream.write(0x00);
outputStream.write(passwd.getBytes());
outputStream.write(0x00);
// After extraction:
private void writeField(OutputStream outputStream, String field) throws Exception {
outputStream.write(field.getBytes());
outputStream.write(0x00);
}
// LoginCommand.write now calls:
writeField(outputStream, userName);
writeField(outputStream, passwd);
Now copy the extracted method — with the identical signature — into the other class. Replace the duplicate fragment in that class with calls to the new method. Run the tests. They must pass.
At the end of this step, both classes have an identical private method with the same name, the same signature, and the same body. This is the deliberate state you are building toward: identical local copies are the precondition for a pull-up.
Why replicate before pulling up: Pulling up to a superclass before both local copies exist means you are designing top-down. That requires you to know the full structure upfront. Replicating bottom-up means you can pull up mechanically — you are not making design decisions, you are moving code that already exists.
If the classes already share a common parent that is appropriate for the shared method, skip to Step 6.
If not, introduce one:
Command as parent of LoginCommand and AddEmployeeCmd).Choose a name that describes what the classes have in common, not what is convenient. If the name is awkward, the superclass boundary may be wrong.
Move the shared method from one subclass to the superclass. Delete the copy in the other subclass. Verify both subclasses now call the superclass version.
Run the tests. They must pass.
// Command (superclass) now holds:
protected void writeField(OutputStream outputStream, String field) throws Exception {
outputStream.write(field.getBytes());
outputStream.write(0x00);
}
// Removed from LoginCommand and AddEmployeeCmd
Return to Step 2. Look at the now-cleaner methods in both classes. Has the first extraction revealed more duplication? Often it has: the removed fragment was obscuring a larger pattern.
Continue extracting, replicating, and pulling up one fragment at a time. Run the tests after every step.
After removing the small fragments, look at what remains. Are the write methods in both subclasses now structurally identical — same steps, different data? That is the Template Method pattern emerging:
writeBody() method.write() method.writeBody().Do not design this structure upfront. Arrive at it by noticing that two method bodies are identical except for one extracted piece. The pattern is a consequence of systematic duplication removal, not a precondition for it.
Orthogonality emerges: When duplication is fully removed, each behavior has exactly one location. To change how fields are written, edit
writeField. To change the message envelope, editwrite. To add a new command variant, subclass and implementwriteBody. This is the open/closed principle made concrete — open for extension (new subclasses), closed to modification (existing methods need not change).
| Input | Required | Description |
|---|---|---|
| Duplicated code sites | Yes | Classes and methods containing the repeated logic |
| Test coverage | Yes | Passing tests covering each duplicated site |
| Shared type relationship | No | Whether classes already share a parent (simplifies Step 5) |
| Output | Description |
|---|---|
| Extraction plan | Ordered list of fragment → local method → pull-up steps, with test runs between each |
| Consolidated code | Shared method(s) in superclass or shared interface; thin subclasses containing only variation |
| Passing test suite | Same tests that existed before, still passing — behavioral proof that extraction preserved correctness |
Start with the SMALLEST duplicated fragment, not the whole method. Large-scale deduplication is the result of many small extractions, not one large one. Small steps are reversible, verifiable, and reveal the next step naturally.
Tests MUST cover the duplication before extraction begins. Without a safety net, a mechanical step that looks correct can silently change behavior. Tests turn this process from "I believe this is safe" to "I know this is safe."
Replicate locally before pulling up. Extract to a local private method in each class first. When both local copies are identical, the pull-up is a mechanical move. This separates the "what to extract" decision from the "where to put it" decision.
Let structure emerge — do not design it upfront. Template Method, common superclasses, abstract methods — these are observations about what the code already implies, not plans imposed on the code. Arrive at them by noticing what is the same.
Coincidental similarity is not duplication. Two classes that have the same 3-line sequence for unrelated reasons should not be coupled. The test: if one copy needed to change, would the other need to change too? Same semantic intent = duplication. Shared syntax, different intent = coincidence.
After consolidation, the open/closed principle is at work. New variations become easier, not harder. A new command subclass only implements its variation. The shared mechanism is inherited. Adding a feature no longer requires changing every copy.
Situation: Two Java command classes both contain the repeated pair outputStream.write(field.getBytes()); outputStream.write(0x00); for every string field they write. Both classes write header, command char, fields, footer — same structure, different fields.
Step 2 — Smallest fragment: The two-line write-and-terminate pair. Name: writeField(OutputStream, String).
Step 3 — Extract locally in LoginCommand:
private void writeField(OutputStream outputStream, String field) throws Exception {
outputStream.write(field.getBytes());
outputStream.write(0x00);
}
Replace all write/0x00 pairs in LoginCommand.write() with writeField(...) calls. Tests pass.
Step 4 — Replicate in AddEmployeeCmd: Same method, identical signature. Replace its pairs. Tests pass.
Step 5 — Introduce superclass: Create abstract Command class. Both classes extend it. Tests pass.
Step 6 — Pull up: Move writeField to Command. Delete local copies. Tests pass.
Step 8 — Emergence: After writeField is shared, both write() methods are structurally identical: header → size → commandChar → writeBody() → footer. Extract writeBody() as abstract. Pull write() to Command. Pull shared constants (header, footer, SIZE_LENGTH). The subclasses reduce to constructor + writeBody() + getCommandChar().
Final state: Command holds all protocol logic. Adding a new command is one subclass, no copy-paste.
Situation: UserValidator and OrderValidator both open with:
if (input == null) {
throw new IllegalArgumentException("input must not be null");
}
The guard is identical across both classes and three other validators as well.
Step 2 — Smallest fragment: The three-line null guard. Candidate name: requireNonNull(Object, String).
Steps 3–4: Extract to local method in UserValidator, replicate in OrderValidator. Tests pass in both.
Step 5: Check — do the validators share a parent? If they all extend a BaseValidator, pull up there. If not, decide: introduce AbstractValidator or extract to a shared utility class (ValidationUtils.requireNonNull). Choose based on whether validators truly share an identity or are only incidentally similar.
Step 8 — Observe: After the guard is shared, look at whether the remaining validation logic also shares structure. If all validators do: guard → validate fields → aggregate errors → return result, Template Method is emerging. Extract validateFields() as abstract and pull the outer structure up.
Situation: FilePermissionChecker and DatabaseConnectionPool each contain:
if (count < 0) {
throw new IllegalArgumentException("count must be non-negative");
}
Analysis: FilePermissionChecker checks the number of retries. DatabaseConnectionPool checks the pool minimum size. These are semantically unrelated. The two classes have nothing in common — no shared parent makes sense, no shared utility class is appropriate.
Decision: do not extract. The similarity is coincidental. If the retry validation rule changes (e.g., to allow 0 retries), you would change FilePermissionChecker but not DatabaseConnectionPool. Coupling them would create false dependencies and make both harder to change.
The test: "If one copy needed to change, would the other need to change too?" Answer here: no. Leave them independent.
references/legacy-code-fundamentals.md — core definitions: legacy code, seams, characterization testsreferences/refactoring-patterns.md — extract method, pull up method, template method mechanicsCC BY-SA 4.0 — BookForge Skills, derived from "Working Effectively with Legacy Code" by Michael C. Feathers. Skill interpretation, structure, and synthesis are original BookForge content.
Direct dependency (run before this skill):
characterization-test-writing — establish the regression safety net that makes each extraction step safeCross-references:
big-class-responsibility-extraction — when duplication removal reveals that a class is still doing too much, apply this next to split remaining responsibilitiesdependency-breaking-technique-executor — the "Pull Up Feature" technique overlaps with pull-up mechanics; use when dependency breaking and duplication removal are both needed in the same class hierarchyWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
refactoring, dry, duplication, legacy-code, extract-method, template-method
npx claudepluginhub bookforge-ai/bookforge-skills --plugin working-effectively-with-legacy-code16 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'./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'./legacy-code-change-algorithmGuide safe modification of legacy code (untested production code) using Feathers' 5-step Legacy Code Change Algorithm. Use this skill whenever a developer needs to change code that lacks test coverage — adding a feature, fixing a bug, refactoring, or optimizing — and wants to avoid regressions. Activates for 'I need to change this code but there are no tests', 'how do I safely modify legacy code', 'inherited codebase', 'untested code', 'legacy system change', 'code without tests', 'refactor without regressions', 'make this code testable', 'cover and modify', 'don't break anything', 'risky change to old code', 'no test coverage', 'adding feature to old code', 'fixing bug in untested code', 'legacy codebase change safely'.Other plugins' skills for the same job