How to Prevent Duplicate Functions in AI Coding Workflows
Part of the AI Code Quality guide. Start with How to Reduce AI Coding Mistakes: A Practical Guide
Suppose an agent adds an email validator to a form. Another version lives in utils/, one sits in services/, and a controller has its own check, so review now has to establish whether they're copies or different policies. The new function's tests can pass while leaving that question unanswered.
I'd want to settle it before another implementation exists.
That means asking for evidence of a lookup, including the candidates that looked promising but didn't fit, the places the agent checked, and the reason it still needs new code. A request to “avoid duplication” leaves all of that invisible.
Require lookup evidence before the first edit
Start with the behavior you need. Search the relevant module and shared packages, look beyond the proposed function name, open candidate implementations, then inspect their callers before deciding what to change.
An email check used to reject malformed input might have a different contract from one that applies an account policy.
Give the agent this prompt:
Before editing, look for an existing implementation of <behavior>.
Search the target module, adjacent modules, and shared packages.
Try alternative names and domain terms, not only my proposed name.
Open promising implementations and inspect their callers and tests.
Return:
- Search terms and paths checked.
- Candidate functions, with file paths and line ranges.
- Relevant behavior differences and affected callers.
- A decision: reuse, extend, or new, with a reason.
If a search or directory was unavailable, say so.
Stop after the lookup and proposed change plan.
The next artifact should be small enough to read in a PR description. This is a template, not a report from a real repository:
Behavior needed: <inputs, expected result, failure behavior>
Repository revision: <revision and local changes considered>
Searches run: <terms, tools, directories>
Candidates inspected: <function, path:lines, caller paths>
Differences: <why each candidate fits or does not>
Decision: <reuse | extend | new>
Change plan: <files and callers to update>
Verification: <behavior tests and production path to exercise>
Search limits: <unavailable paths or unresolved questions>
Keep a rejected candidate in the record when the difference matters, especially if the same search will find it again, so the next reviewer can see why it wasn't reused, rather than restarting the comparison. For the lookup itself, here's how to search for an existing function before writing one.
What a real function search gives you
I build Pharaoh. It maps TypeScript, JavaScript, Python, C and C++ repositories into a code knowledge graph and exposes architectural information over MCP, including function locations, signatures, module context, and the callers affected by a change.
search_functions was run for formatPrice, with a limit of 8, against the public repository Pharaoh-so/cal.diy, revision 54343aa6. Only the first match is shown below:
# Search Results: "formatPrice" (showing 1-8)
- const formatPrice = (price: number, currency: string | undefined, locale = "en") => ... [exported, complexity: 3]
packages/lib/currencyConversions.ts:60-71 (lib)
Now the agent has a candidate it can open. The path and signature support that next step, but don't prove that the function implements the requested behavior, handles the required edge cases, or should be shared with another module.
get_module_context, which returns exports and dependencies, gives you module context to inspect before changing a candidate, alongside the affected production callers returned by get_blast_radius. The consuming agent still has to compare the implementations.
There's a branch limit to account for. Pharaoh's graph covers the default branch of a live repository, re-maps it on every push to that branch, and excludes feature-branch edits and uncommitted work, so inspect the working tree as part of the lookup. A graph result isn't a substitute for reading a candidate that changed locally.
Decide whether to reuse, extend, or write something new
Finding a similar function doesn't mean you should merge everything into it. I'd use this decision rule:
| Decision | Evidence to show | Change to make |
|---|---|---|
| Reuse | An existing function already meets the required contract. | Import it and exercise the new caller. |
| Extend | The existing function owns the behavior, but lacks a needed case. | Check its callers and add the case with regression coverage. |
| New | Existing candidates implement a different policy or cannot serve this caller safely. | Explain the boundary and give the new function a name that reflects it. |
For the hypothetical email validators, compare the accepted inputs, failure behavior, normalization rules, and callers before choosing one. If they're meant to enforce different policies, keep that distinction explicit. If they implement the same rule, update the consumers as part of the change.
A new function needs a reason someone else can inspect.
What the research measures
The evidence is useful, but the studies measure different things, cover different populations, and don't establish the cause of any duplicate in your repository. Keep those limits attached to the numbers.
GitClear's 2025 analysis examined 211 million changed lines from 2020 through 2024 and reported that lines it classified as copy/pasted rose from 8.3% of changed lines in 2021 to 12.3% in 2024, but those aggregate figures cannot tell you whether a new function in your PR duplicates an existing helper, or establish that the duplicate was caused by an assistant rather than another authoring process.
The 2024 DORA findings reported that as AI adoption increased, it was accompanied by an estimated 1.5% decrease in delivery throughput and an estimated 7.2% reduction in delivery stability, which concerns delivery outcomes, not a measurement of duplicate functions, and shouldn't be read as proof that duplication caused those results.
And Code Copycat Conundrum studied 19 code models across three benchmarks, identified repetition at several granularities in generated output, and organized it into 20 patterns, including character repetition as well as repeated statements and blocks, rather than counting helpers already implemented elsewhere in a repository.
For your own AI-generated technical debt, inspect what changed, record confirmed duplicates separately from scanner candidates, and keep a baseline, rather than treating one of these studies as your team's duplication rate.
Can AI identify duplicated code already in a repository?
Yes, you can ask an agent to find candidates and compare their behavior, but require paths and code evidence, inspect its reasoning, and test the differences before accepting an equivalence claim. A confident summary alone gives a reviewer too little to check.
Run a clone scan for existing duplicates
jscpd's README documents this command for a first pass:
npx jscpd .
Run it at the repository root. Review the reported locations before proposing a refactor.
jscpd's default comparison matches identical token sequences, which gives you reproducible clone candidates, not a decision about their business purpose, their callers, or whether sharing them would introduce the wrong dependency. jscpd also documents experimental semantic scanning, so its default scan shouldn't be confused with everything the tool can attempt.
If you already use another scanner, keep the distinction between its findings and a refactoring decision:
| Tool | What to inspect |
|---|---|
| PMD CPD | Token-based duplicate matches and the configured minimum token length. |
| SonarQube duplication metrics | Duplicated blocks and lines, including duplication density on new code. |
Keep the scanner configuration stable when comparing runs, record deliberate exclusions such as generated code, review new findings against the baseline, and confirm behavior before removing a copy. A falling percentage alone doesn't tell you whether the intended callers now share the right implementation.
Compare behavior across modules
These are illustrative review cases, not findings from a customer repository:
For a retry helper in network/ and another in orders/, compare the retryable failures, attempt limits, timeout behavior, and side effects before extracting anything shared. A helper that repeats an operation may be unsuitable for a caller whose operation must happen only once.
With Slack payload builders in notification and billing modules, inspect the constructed fields, formatting rules, error handling, and the code that sends the payloads. Matching output construction may belong in a shared function. Different message policies may still belong with their callers.
For two onboarding flows with account normalization, trace the active entry paths, compare the normalization rules, check whether both paths are still used, and decide whether either copy should be removed. Similar code in an abandoned flow is a different cleanup task from two live flows that need the same fix.
An agent's comparison should identify the input that would expose a difference. Turn that into a test before deciding the functions are interchangeable.
Keep the change small enough to review
Work on a feature branch, checkpoint completed changes with descriptive commits, keep unrelated cleanup out of the patch, and inspect the diff before merging. That makes a duplicate-removal change easier to review and reverse if its assumptions were wrong.
When extending a shared helper, test existing caller behavior as well as the new case. When replacing a copy, exercise the endpoint or job that should now reach the shared implementation.
Watch for new code that never gets wired in, especially after an extraction, because tests of the shared helper can pass while a production caller still imports the old version, or bypasses it, or never reaches it at all.
Pharaoh's PR Guard is available on Pro, checks new dead code and breaking signature changes as well as exact function duplicates and blast radius, and posts an advisory neutral check by default, so its presence doesn't mean a merge is blocked. Its exact-duplicate check doesn't establish semantic equivalence between different implementations.
search_functions and module context are available to your agent when you set up Pharaoh for a TypeScript, JavaScript, Python, C or C++ repository. Keep the lookup artifact in the PR, whichever search tool you use, so a reviewer can follow the decision, check the candidates, and see why this change belongs here.
FAQ: Preventing duplicate functions in AI coding workflows
How do I prevent an AI coding agent from creating a duplicate function?
Require the agent to search the target module, adjacent modules, and shared packages before editing. It should try alternative names and domain terms, inspect candidate implementations, callers, and tests, then state whether to reuse, extend, or create a new function and explain why.
How can I tell whether two functions are truly duplicates?
Compare their inputs, outputs, failure behavior, normalization rules, side effects, callers, and relevant edge cases. A clone scanner can provide candidates, but it does not decide whether the functions have the same business purpose or can safely be shared.
Should I reuse, extend, or write a new function?
Reuse an existing function when it already meets the required contract. Extend it when it owns the behavior but lacks a needed case. Write a new function when existing candidates implement a different policy or cannot safely serve the caller; document that boundary.
How should I verify that duplicate-function cleanup worked?
Inspect the diff, test existing caller behavior and the new case, and exercise the endpoint or job that should reach the shared implementation. Confirm that production callers no longer import, bypass, or fail to reach the intended helper.
Article Record
ReferencesPrimary sources used for this article
- Code Copycat Conundrum: Demystifying Repetition in LLM-based Code Generation
- Understanding measures and metrics
- Finding duplicated code with CPD
- jscpd
- rust.md
- AI Copilot Code Quality: 2025 Look Back at 12 Months of Data
- HyClone: Bridging LLM Understanding and Dynamic Execution for Semantic Code Clone Detection
- Meet the Workflows: Continuous Simplicity
Update HistoryMeaningful revisions to this article
- Added four frequently asked questions to help readers find practical answers more easily.