Direct answer
Decide between extracting shared code and keeping copies separate by looking at why each copy changes, not at how similar the lines look. Matching text is a clue. Matching reasons to change are the stronger signal. When two blocks serve different owners or evolve under different rules, leave them apart even if they are nearly identical today.
SonarSource includes readability, clarity, reliability, and modularity in its code-quality framing (F043, official), which supports treating duplication as one signal among several rather than a defect to eliminate on sight. Before consolidating, compare ownership and change history with git log (F045, derived). Before removing or altering a public API, check compatibility, because SemVer treats an incompatible public API change as a major-version concern (F044, official).
The extraction is justified when the copies share a contract that is already stable. Until then, a deliberate, documented copy is often the cheaper and safer choice.
Why a blanket anti-duplication rule costs more than it saves
The reflex is familiar: find repeated lines, extract a helper, call it from both places, and move on. Sometimes that is right. Applied as a blanket rule, it produces abstractions that are harder to change than the copies they replaced.
The mechanism is a coupling problem. Two blocks that looked identical often differ in a dimension nobody noticed at extraction time. Once they share an implementation, every change has to satisfy both callers. A parameter appears to handle the difference. Then a second parameter. Then a flag that selects between behaviors. The helper grows a config surface, and the reviewer now has to reason about two call sites plus every combination of options to understand either one.
The cost arrives in three forms. Changes become slower because a modification that used to touch one copy now has to be checked against every consumer of the shared contract. Risk rises because a fix for one caller silently changes another. And the abstraction itself becomes a maintenance item, since somebody has to keep its signature coherent as the callers drift.
There is also a line-count trap. Fewer lines are not automatically better design. Deleting a copy by forcing two behaviors through one function can hide a genuine difference behind a boolean, which is a readability loss recorded as a win.
Duplication is worth investigating, not worth erasing on sight. The question is whether the copies are the same behavior by accident or by contract.
Find the duplicated behavior
Start by identifying what is actually duplicated, which is not always the same as which text matches. Two blocks can share text and implement different behaviors, or differ in text and implement the same behavior.
Search for repeated logic by shape rather than by string. Look for the same sequence of operations over the same kinds of data: a validation followed by a transformation followed by a write, a loop that accumulates a total, a guard that rejects the same condition. Those are the candidates worth comparing.
| Duplicated behavior | Copies | Owners | Change history |
|---|---|---|---|
| Currency rounding before display | Web UI and invoice service | Frontend team, billing team | Both changed for different rounding rules |
| Address normalization before save | Checkout and CRM sync | Platform team, both | One change, both copies updated together |
| Retry with backoff around an HTTP call | Three services | Same platform owner | Changes apply to all three at once |
| Discount application logic | Retail and wholesale paths | Same pricing owner | Rules diverged; copies now differ in behavior |
Each row points to a different decision. Currency rounding has different owners and different rules, so it is a candidate for independence. Address normalization changed together and has one owner, so it is a candidate for extraction. Retry logic changed together under one owner, the strongest extraction signal. Discount logic has already diverged, so forcing it back together would be a behavior change.
Compare the reason for each copy
The reason a block changes is the decisive evidence. Two copies with the same reason to change belong together. Two copies with different reasons to change should stay apart, whatever their text says.
Ask a specific question of each copy: what would have to change in the outside world for this block to need editing? If the answer is the same for both, the copies share a reason and consolidation is worth pursuing. If the answers differ, the copies are independent and extraction would couple things that should not be coupled.
| Question | Copy A answer | Copy B answer | Shared reason? | Decision |
|---|---|---|---|---|
| What triggers a change here? | New payment provider | New tax jurisdiction | No | Keep separate |
| What breaks if the rule is wrong? | Payment fails | Tax report is wrong | No | Keep separate |
| Who decides the rule? | Payments owner | Finance owner | No | Keep separate |
| Does the rule change with the domain or the plumbing? | Domain | Plumbing | No | Keep separate |
| Would a fix apply to both? | Yes | Yes | Yes | Consider extraction |
That table is the core of the decision. Note that “keep separate” is the answer for most rows even when the code looks identical. That is the point. Text similarity is not the test.
A shared reason does not guarantee extraction is right. The contract also has to be clear enough to state. If you cannot write down what the shared behavior guarantees, you are not ready to extract; you would be guessing at an interface and discovering the real contract through breakage.
Check ownership and change history
Ownership and history are evidence, not proof. They tell you how the copies have behaved so far, which is the best available predictor of how they will behave next.
Use git log to see how often each copy changed and whether changes landed together or separately. Use git show on the relevant commits to see what actually changed. Two copies that were updated in the same commits, by the same authors, for the same reason are strong extraction candidates. Two copies that drifted apart through independent commits are telling you they are independent.
F045 is explicit that history is evidence about change patterns and not proof that copies should be merged (derived). A copy may be quiet because nobody has needed it yet, not because it is truly shared. Treat a short history as a reason to wait rather than a reason to act.
| Evidence from history | What it suggests | Confidence | Action |
|---|---|---|---|
| Changes land in the same commits | Shared reason to change | High | Extraction candidate |
| Same author, same day, both copies | Deliberate coordination | High | Extraction candidate |
| Changes drift apart over months | Independent evolution | High | Keep separate |
| One copy never changes | Unknown, possibly unused | Low | Check usage before deciding |
| History is very short | Not enough evidence | Low | Wait for more signal |
The quiet copy deserves a usage check before any decision, including deletion. The dead code usage evidence guide covers how to prove whether something is actually used before removing it, which is a prerequisite for consolidation too.
Identify the stable shared contract
An extraction needs a contract: a statement of what the shared code guarantees to every caller. The contract has to be true today and stable enough to be worth depending on.
Write the contract before writing the abstraction. A contract names the inputs, the guarantee, the error behavior, and what is explicitly out of scope. If you cannot state it in a few sentences, the copies do not yet share a contract and extraction would be premature.
| Shared contract | Differing behavior | Extraction decision | Why |
|---|---|---|---|
| Round a decimal to two places, half up | None between callers | Extract | Contract is exact and stable |
| Normalize whitespace and case in an address | One caller strips punctuation | Extract core, keep the difference at the caller | Difference is caller-specific policy |
| Retry a failed HTTP call with backoff | Different retry counts | Extract with a bounded parameter | Count is a bounded, declared option |
| Apply a discount by customer segment | Rules differ per segment | Do not extract | Rules are the caller’s domain logic |
The third row is the common compromise: extract the stable core and let each caller supply the bounded variation. The parameter must be declared, bounded, and documented. An unbounded parameter, one that can encode any behavior, is not a contract; it is a function that takes instructions.
The last row is the trap. Discount rules that differ per segment are domain logic, and hiding them behind a generic helper obscures the rules. A generic helper that silently encodes one segment’s policy as the default is worse than two visible copies.
Avoid extracting before the shared contract is clear. A premature abstraction is one discovered through breakage rather than stated up front, and it tends to grow flags until it is worse than the copies it replaced.
Extract only the common behavior
When the contract is clear, extract the part that is genuinely common and leave the variation at the callers. The extraction should be behavior-preserving: every caller gets the same result it got before, on the same inputs.
Keep the extraction narrow. Move the common operation, not the surrounding context. If the two copies differ in how they acquire data, log, or handle errors, leave those differences in place rather than pulling them into the shared unit.
| Copy | Common behavior to extract | Variation to leave behind | Caller change |
|---|---|---|---|
| Web and invoice rounding | Decimal rounding to two places, half up | Where the value is displayed | Call the shared function |
| Checkout and CRM address | Whitespace and case normalization | Punctuation stripping policy | Call core, then apply local policy |
| Three retry wrappers | Backoff schedule computation | Endpoint, error classification | Call shared backoff |
The variation left behind is as important as the behavior extracted. If a caller keeps a local step after calling the shared core, that step is visible and reviewable. If it is folded into a parameter, it becomes an option future readers have to trace.
Keep deliberate duplication documented
When you decide to keep copies separate, record why. A documented copy is a decision. An undocumented copy is a target for the next cleanup pass.
The record should be short and located where the next reader will find it: a comment near the copy, a note in the module readme, or a line in the decision log. State that the similarity to another module is intentional, name the dimension along which the copies are expected to diverge, and give the condition under which extraction would become worthwhile.
| Kept copy | Reason it is separate | Expected divergence | Extraction trigger |
|---|---|---|---|
| Web currency formatter | Different rounding rule than billing | Per-market display rules | Rules converge or one owner takes both |
| Wholesale discount path | Rules differ per segment | Segment-specific pricing policy | Segments share a rule set |
| Service A validation | Independent domain authority | A’s own field requirements | A shared schema is adopted |
This documentation does double duty. It stops a well-meaning refactor from merging independent behavior, and it tells the next person what evidence would change the decision. That is the same habit as naming a review date for a quarantined test in the flaky test triage guide: an exception with an owner and a condition is managed, while an unexplained one just drifts.
Ask Claude Code to challenge the abstraction
An abstraction proposal is exactly the kind of thing worth arguing with before accepting. Ask the agent to state the contract it is extracting, list every caller, and identify which caller behaviors differ. Then challenge it.
Official best practices recommend precise prompts with file names and symptoms, and a pass-or-fail check so the agent can close a work loop. Applied here, name both copies and ask for the differing behavior explicitly:
These two functions look identical. Restate what each guarantees to its caller, list every call site of each, and identify any behavior that differs between them. If they share a contract, propose extracting only the common part and leave caller-specific policy at the call sites. If they do not share a contract, say so and recommend keeping them separate.
Then verify the claim. Read the call sites yourself. An agent that misses a dynamic dispatch site or a reflection-based caller will propose an extraction that breaks a consumer nobody listed. Dynamic references are covered in the dead code usage evidence guide, and the same caution applies to consolidation.
A useful follow-up is to ask the agent to argue against its own proposal: which caller is most likely to need a different behavior next, and would the shared signature accommodate it? If the answer requires a new flag, that is a sign the copies are more independent than they looked.
Verify both callers after extraction
An extraction is not done when the code compiles. It is done when every caller has been checked against the contract and the behavior is confirmed unchanged.
The verification is behavioral, not structural. For each caller, run the representative inputs through the before and after and compare the observable results. A test that already covered the caller is the cheapest evidence. Where coverage is thin, add a focused check before extracting so the comparison is possible.
| Caller | Verification check | Compatibility impact | Follow-up |
|---|---|---|---|
| Web UI | Display values match before and after | None if internal | None |
| Invoice service | Invoice totals match to the cent | None if internal | None |
| Public SDK method | Output and error contract unchanged | Potentially major if changed | SemVer review |
| Generated client | Regenerated output unchanged | Depends on generator | Re-run generation |
The public SDK row is the one that changes the decision. If either copy is part of a published API, altering its signature or observable behavior is a compatibility event. SemVer requires a major increment for an incompatible public API change (F044, official), and whether a symbol counts as public API depends on the project’s documented contract. An internal helper extraction may have no public API impact, but that has to be checked rather than assumed.
When the extraction does alter a published contract, route it through the version decision in the SemVer compatibility guide and record the consumer impact in the changelog. Do not fold a breaking change into a cleanup commit.
Worked example: two rounding blocks
Suppose a web UI and an invoice service both contain a block that rounds a decimal to two places before display. The text is nearly identical. A cleanup pass flags both.
History check: git log shows the web block changed twice in a year for display formatting, and the invoice block changed once for a tax-rounding correction. Different owners, different triggers. The reasons to change differ.
Contract check: the web block rounds half up for display. The invoice block rounds half up for tax computation but rejects negative values first. The rejection is caller-specific policy, not shared behavior.
Decision: extract only the rounding operation, which is genuinely common, and leave the negative-value rejection in the invoice caller. The shared unit is a function that takes a decimal and returns it rounded to two places, half up.
Derived arithmetic for the review fixture, using stated inputs only: value 10.005 rounded half up to two places is 10.01. Value 10.004 rounded the same way is 10.00. Value -1.005 reaches the invoice caller, hits the caller’s negative-value rejection, and never reaches the shared rounding function. These inputs and the rounding rule come from the fixture, not from any external standard, and they exist so both callers can be compared against the same expected values.
The concrete win is one rounding definition instead of two, so a future change to the rounding rule has one place to land. The concrete loss is that the negative-value policy now lives only in the invoice caller, and a future reader has to notice that the shared function does not reject negatives. That is why the kept variation needs a note at the call site.
Practical checklist and runbook
- Find the duplicated behavior by shape, not by exact string match.
- Ask what triggers a change in each copy. Same trigger means a shared reason.
- Check ownership. Different owners with different authority usually mean independence.
- Pull the history with
git logand inspect the relevant commits withgit show. - Write the shared contract if one exists. Inputs, guarantee, error behavior, out of scope.
- Decide extract or keep. No clear contract means keep separate for now.
- Extract only the common part. Leave caller-specific policy at the call sites.
- Document kept copies. Name the expected divergence and the extraction trigger.
- Verify every caller. Compare before and after on representative inputs.
- Check compatibility for any published API before merging the change.
| Gate | Pass condition | Failure response |
|---|---|---|
| Reason to change | Same trigger for both copies | Keep them separate |
| Ownership | Compatible or identical authority | Keep them separate |
| History | Changes landed together | Keep them separate |
| Contract | Stated in a few sentences | Do not extract yet |
| Callers | All call sites enumerated | Find dynamic references first |
| Compatibility | Published API unchanged, or reviewed | Route through SemVer |
The practical implication: spend the comparison time before the extraction, not after. Ten minutes of history and contract writing prevents an abstraction that couples two domains and grows flags for a year.
Concrete win, honest loss, and next decision
Win: When the copies share a reason to change and a stated contract, extraction gives the behavior one definition. A future rule change lands in one place, both callers get it, and the reviewer compares against a written contract instead of reading two implementations.
Loss: The comparison can be wrong. A short history hides a divergence that has not happened yet, a dynamic caller may not appear in the enumerated list, and a contract that seemed stable can split the first time a new requirement arrives. Once coupled, separating the copies again costs more than the original duplication did.
Implication: Default to keeping copies separate until the shared contract is clear and the change history supports it. Extract when the evidence is strong and the variation is bounded. Document the copies you keep so the next cleanup pass does not re-litigate the decision.
Where this fits in the batch
Duplication is one of several quality signals competing for the same attention. Ranking complexity hotspots covers the branching and change-frequency side of the same ranking problem. Baselining static analysis findings covers inherited debt so a duplication rule does not become an unusable backlog.
Deletion is often the better first move. Proving usage before removing dead code handles the case where a copy is quiet because nothing calls it. Recovering stashed experiments safely applies when an extraction needs to be set aside.
Extraction is a behavior-preserving change, so the testing side matters. Mapping changed code to a check set tells you which tests to run, and isolating fixture state keeps the comparison clean between cases. For contracts that cross a service boundary, contract tests for API expectations verify the interactions a consumer actually relies on.
When the shared code is a published API, SemVer compatibility decisions govern the version impact and consumer-facing changelog entries record it. Release tag verification ties the change to the exact candidate.
Extraction findings belong in the analyzer baseline too. Baselining static analysis noise keeps a duplication rule from turning into an unusable backlog, and when a copy turns out to be unreachable, proving usage before removal settles it faster than refactoring.
For the surrounding workflow, verification and what to ask for when it says done governs how the extraction claim is checked, and the cost per verified change frames why a bounded diff is worth protecting. Behavior-preserving changes travel through review like any other, so atomic, revertible commits keep an extraction reviewable and resolving merge conflicts by behavior applies when two extractions touch the same block.
Data gap and future update
SonarSource’s inclusion of readability, clarity, reliability, and modularity in its quality framing is vendor guidance and does not prescribe a single abstraction rule for duplicated code (F043, official). SemVer’s treatment of incompatible public API changes as a major concern is from the specification (F044, official). The recommendation to compare ownership and change history before consolidating is derived from the Git documentation rather than being a built-in feature or a universal rule (F045, derived).
No measured claim is made here about how much duplication costs, how much extraction saves, or what defect rates follow from either choice. The fact pack contains no such benchmark. Whether a symbol is public API depends on each project’s documented contract, which is not part of the source set.
Change-history interpretation depends on repository conventions that vary by team. Commit granularity differs, so “changed together” is stronger evidence in a repository with fine-grained commits than in one that batches many changes per commit. Documentation and tooling can change after the 2026-11-28 research date.
One AI API Key option for OpenAI-format agents
Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The research packet records Claude IDs as unavailable on 2026-11-27.
For a separate OpenAI-format agent, One AI API Key provides https://api.oneaiapikey.com/v1, a single key, and 46 live free IDs. That option concerns a different client and request format, not a way to run Claude Code. Review the free model list and eligibility details or read the quickstart before choosing an agent route.
FAQ
Should all duplicated code be extracted?
No. Extract when the copies share a reason to change and a contract you can state. Keep copies separate when their owners, triggers, or rules differ, even if the text looks identical.
How do I know if the shared contract is stable enough?
Check the history. If changes to the copies have landed together for the same reason, the contract has been stable in practice. If they drifted, the contract is not shared. F045 treats history as evidence about change patterns, not proof.
Does extracting a helper count as a breaking change?
Only if it alters a published API. SemVer requires a major increment for an incompatible public API change (F044). Whether a symbol is public depends on the project’s documented contract, so check before assuming an internal extraction is safe.
What if the two copies have almost no history?
Treat that as insufficient evidence and wait. A quiet copy may be unused rather than shared. Verify usage first with the approach in the dead code evidence guide, then re-evaluate.
Can Claude Code find every caller automatically?
It can enumerate call sites it can see, but dynamic dispatch, reflection, and configuration-driven references can escape a static search. Verify the caller list yourself before merging an extraction.
More Claude Code troubleshooting
- Claude Code Deterministic Tests: Control Time and Randomness
- Claude Code Snapshot Review: Inspect the Diff, Not the Green
- Claude Code Property Tests: Generate Edge Cases
- Claude Code Mutation Testing: Find Weak Assertions
- Claude Code Minimal Repro: Shrink the Failure
- Claude Code Debug Log: Separate Facts from Hypotheses
- Claude Code Async Races: Make Scheduling Deterministic
- Claude Code Memory Leaks: Compare Allocation Snapshots
- Claude Code Git Bisect: Automate Regression Hunts
- Claude Code Git Rebase: Choose a Branch Policy
- Claude Code Commit Messages: Encode Change Intent
- Claude Code Merge Queue: Recover Failed Groups
- Claude Code Branch Protection: Define Merge Checks
- Claude Code Hotfix Backports: Cherry-Pick Carefully
- Claude Code Rollback: Plan a Revert Before Release
- Claude Code Release Checklist: Verify the Candidate
Sources
- Official: SonarSource code quality guide, supporting readability, clarity, reliability, and modularity in the quality framing (F043).
- Official: SonarQube Server documentation, supporting version-specific duplication detection behavior.
- Official: Git log, supporting change-history comparison across copies (F045).
- Official: Git show, supporting inspection of the commits that changed each copy.
- Official: Semantic Versioning 2.0.0, supporting the major-version requirement for incompatible public API changes (F044).
- Official: Claude Code best practices, supporting precise prompts and a pass-or-fail check that closes a work loop.