Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

The reliable way to prevent duplicate code is to make reuse a required decision before implementation. Ask the agent to inspect the relevant behavior, search for existing functions, components, tests, and configuration, read the strongest matches, and explain whether one can be extended. Permit a new helper or abstraction only when the agent can state why the existing candidates do not fit, then review the final diff for parallel implementations and scope creep.

This workflow reduces accidental duplication without pretending that an instruction file can guarantee perfect results. Agents still need accurate repository context, project-specific conventions, tests in the local style, and human review of what they changed.

Why coding agents create duplicate or unnecessary code

An agent usually optimizes for completing the requested behavior from the context it can see. If it cannot find an existing implementation, misunderstands the architecture, or receives a vague request, it may create a new helper, component, service, fixture, or configuration path that overlaps with code already in the repository.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Duplication is not limited to identical functions. Common forms include:

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
  • A second formatter, validator, API client, permission check, or date utility with slightly different edge-case behavior.
  • A new UI component that renders the same pattern as an existing component under a different name.
  • A parallel test fixture or factory instead of extending the established one.
  • A new abstraction introduced for a one-off change when a nearby function already provides the needed seam.
  • Repeated configuration, scripts, data-loading logic, or error handling copied into a new module.
  • Unrelated cleanup, renaming, or refactoring that expands the patch beyond the requested behavior.

The cost is cumulative. Two implementations can drift, tests may cover only one path, future agents may choose the wrong version, and maintainers must learn more concepts to make a small change. The solution is a sequence of explicit decisions rather than a single magic prompt.

The inspection-first workflow

Use the following sequence for every non-trivial change. It works as a standing repository rule and as a task-specific prompt.

  1. Define the requested behavior and boundaries. State what must change, what must not change, and how success will be verified.
  2. Ask for repository inspection before implementation. Have the agent identify the files involved, trace the current behavior, and search for existing code that may already solve the problem.
  3. Require a reuse decision. Ask it to name the best candidates, compare their fit, and choose one to extend or explicitly reject each candidate with a reason.
  4. Read the selected implementation and nearby examples. The agent should inspect callers, related modules, and reference tests before proposing edits.
  5. Implement the smallest compatible change. Follow local naming, layering, error handling, and dependency conventions instead of introducing a parallel pattern.
  6. Extend tests in the repository’s existing style. Inspect both implementation tests and neighboring reference tests before adding coverage.
  7. Review the diff for duplication and scope. Look for second helpers, competing abstractions, duplicate fixtures, new files that are not needed, and unrelated cleanup.
  8. Run the relevant checks and report uncertainty. The agent should state which tests and commands ran, what was not run, and any remaining compatibility concern.

This order matters. Asking for code first and review later gives the agent an incentive to defend a design it has already created. Inspection first makes reuse part of the implementation plan.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Step 1: Ask the agent to inspect before it writes

Your first request should produce an investigation, not a patch. Ask the agent to:

  • Locate the entry point for the requested behavior.
  • Trace the relevant call path, including adapters, services, state, and error handling.
  • Search by domain terms, exported symbols, filenames, route names, event names, and distinctive strings.
  • Find existing tests, fixtures, factories, schemas, and configuration used by the same behavior.
  • Read the most relevant matches rather than relying on search-result names.
  • Report the files inspected and the evidence that each candidate is or is not applicable.

A useful first-turn request is: “Do not edit yet. Trace how this behavior currently works, search the repository for existing implementations and tests that cover it, and list the candidates you would reuse. Explain any gaps or ambiguity.”

Search should be semantic as well as textual. A function called normalizeInput may be the right implementation even if the request uses the phrase “clean user data.” Conversely, a similarly named function may belong to a different boundary or have incompatible assumptions. Reading the body, callers, and tests is what distinguishes a genuine reuse candidate from a misleading name match.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Step 2: Make reuse an explicit decision

Do not leave reuse as an implied preference. Add a decision gate to the prompt or repository instructions:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Only generate new code if no suitable existing solution is found.”

This sentence is documented in Cursor’s reuse guidance. Treat it as a decision rule, not a guarantee. A suitable solution must satisfy the requested behavior and fit the repository’s current boundaries, conventions, and compatibility requirements.

Require a short candidate report before implementation:

  • Candidate: file and symbol, or the relevant component, test fixture, or configuration block.
  • What it already does: behavior demonstrated by its implementation and tests.
  • Fit: why it matches the new requirement.
  • Gap: the smallest change needed, if any.
  • Decision: extend, call as-is, or reject.
  • Reason for rejection: a concrete incompatibility such as a different data contract, lifecycle, performance requirement, or public API.

“I could not find anything” is not enough. The agent should describe the search terms and areas it inspected so you can tell whether the conclusion is credible.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to decide between reuse and a new implementation

When an existing implementation is close but imperfect, compare it on three dimensions before adding anything:

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
Dimension Questions to ask Preferred outcome
Behavioral fit Does it handle the required inputs, errors, security rules, and edge cases? Extend it when the missing behavior belongs to the same responsibility.
Compatibility Does using it preserve current APIs, layering, naming, and dependency conventions? Reuse it when callers can adopt it without an incompatible contract.
Maintenance impact Will one implementation remain the source of truth, or will a change create two versions to maintain? Prefer one shared path unless separation is a deliberate boundary.

A new implementation is justified when the existing code has a genuinely different responsibility or contract, cannot meet the requirement without breaking callers, or would create an unsafe coupling. Record that reason in the change description and, when useful, in a focused code comment. Do not create a second abstraction merely because the existing name is inconvenient or because a fresh design feels cleaner.

Step 3: Give the agent accurate repository context

Agents make better reuse decisions when the repository’s architecture and conventions are written down. Maintain a concise instruction file in the location supported by your editor or agent. Include information that is specific to the project and difficult to infer reliably from source alone:

  • System boundaries, major packages, and the direction of dependencies.
  • Important directories and the role of each one.
  • Supported runtime, package manager, build system, and test commands.
  • Where shared utilities, UI primitives, API clients, schemas, and fixtures live.
  • Public API, backwards-compatibility, security, and migration expectations.
  • Naming, formatting, error-handling, logging, and import conventions.
  • Required checks before a change is complete.
  • Rules for generated files, database changes, feature flags, and ownership boundaries.

Visual Studio Code’s guidance on configuring AI for a codebase recommends keeping instructions focused on important repository-specific knowledge and removing stale or duplicate rules. That maintenance is part of duplication prevention: contradictory instruction files can cause an agent to follow the wrong pattern or generate another version of an existing helper.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not fill the file with generic advice such as “write clean code.” Replace it with observable decisions, for example which package owns validation, which test command covers a service, or whether a component must come from an established design-system directory. Update or delete rules when the architecture changes.

A reusable repository instruction

Before adding a helper, component, service, configuration block, or test fixture, search the repository for existing code that serves the same purpose. Read the most relevant matches and reuse an appropriate implementation or extend it in place. If you add a new implementation, list the existing candidates you checked and explain why each one does not fit. Trace the current behavior before editing, follow nearby implementation and test conventions, keep the change within the requested scope, and run the relevant project checks.

Adapt this rule to the actual project. Add real directory names, commands, and boundaries only when they are true; invented paths make the instruction less useful and can misdirect an agent.

Standing instructions versus task-specific prompts

Use both layers, but for different purposes.

Approach Persistence Specificity Maintenance cost Best use
Repository instruction Applies across tasks Project-wide architecture and conventions Requires periodic review as the codebase changes Stable rules such as search-before-add, ownership boundaries, and required checks
Task-specific prompt Applies only to one request Exact feature, files, constraints, and acceptance criteria Low after the task ends Temporary scope, migration limits, compatibility details, or a particular reuse decision

A standing rule should not contain assumptions that are true only for one ticket. A task prompt should repeat the relevant reuse gate when the change is risky, touches unfamiliar code, or has an unusually narrow scope. If the two conflict, resolve the conflict explicitly before asking for implementation.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Step 4: Explore behavior before editing

Ask the agent to explain the current code path in plain language before it proposes a patch. The explanation should identify:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Where input enters the system and where output is consumed.
  • Which module owns the behavior and which modules merely adapt it.
  • Existing validation, authorization, caching, retries, and error translation.
  • Side effects, transaction boundaries, asynchronous behavior, and lifecycle assumptions.
  • Tests that demonstrate the expected behavior and known edge cases.

Visual Studio Code’s guide to exploring a codebase with an agent emphasizes investigating existing behavior and reviewing generated project notes before promoting them to shared documentation. Treat an agent’s summary as a navigation aid, not as authoritative architecture. Check its claims against the source before adding them to an instruction file. Otherwise, an incorrect summary can become a durable rule that encourages future duplication.

For a large repository, narrow the exploration deliberately: identify the package, entry point, and likely ownership boundary first, then expand only when imports, tests, or runtime flow require it. This reduces the chance that the agent invents a new cross-cutting abstraction simply because it has not found the existing one.

Step 5: Extend tests in the existing style

Tests are a frequent source of unnecessary code. An agent may create a new fixture, factory, mock, or test utility even though neighboring tests already show the accepted pattern. Before asking for test changes, require it to inspect:

  • The implementation under test and its public entry point.
  • Several nearby tests for the same module or feature.
  • Shared fixtures, factories, builders, stubs, and setup hooks.
  • Assertions used for equivalent success, failure, boundary, and authorization cases.
  • The command and environment used to run the relevant test subset.

Anthropic’s Claude Code developer-use-case guidance illustrates this approach: read the implementation and reference tests, then match existing test conventions. “Matching” should include fixture lifecycle, naming, isolation, async handling, and assertion style, not just indentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prefer extending a shared fixture when the new data is a legitimate variation of the same domain object. Create a separate fixture when the test represents a different contract or lifecycle and combining them would obscure intent. In either case, ask the agent to explain why a new test helper is necessary.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Step 6: Keep the implementation within scope

Agents often identify genuine improvements while working. Those improvements can still be wrong for the current change. Set explicit boundaries:

  • Name the behavior that must change.
  • List files or subsystems that are out of scope, when known.
  • Do not rename, reformat, migrate, or reorganize unrelated code.
  • Do not introduce a general-purpose abstraction for a single call site unless reuse is already demonstrated.
  • Separate required compatibility fixes from optional cleanup.
  • Put follow-up ideas in a note or issue rather than silently adding them to the patch.

When the agent proposes a broader refactor, ask for two plans: the smallest change that satisfies the request and the broader redesign as a separate option. Implement the smaller plan unless the broader one is required for correctness, security, or an explicitly approved migration.

Step 7: Review the diff for duplication

Do not review only the changed lines. Inspect the complete diff and the new file list. Use this checklist:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Does the patch add a helper, component, service, fixture, or configuration block that overlaps an existing one?
  • Could an existing function be extended instead of copied?
  • Does a new abstraction have more than one real consumer, or is it speculative?
  • Are imports, routes, schemas, and exports duplicated under different names?
  • Did the agent create a second error-handling, validation, or formatting path?
  • Are tests using the established fixture and assertion conventions?
  • Are generated files or snapshots changed only when required?
  • Did unrelated formatting, renaming, dependency upgrades, or cleanup enter the diff?
  • Does each new file have a clear owner and a reason tied to the requested behavior?

For every new symbol, ask: “Why is this not an extension or call to an existing symbol?” For every deleted or bypassed path, ask: “What behavior and tests prove that the old path is no longer needed?” These questions expose parallel implementations that a line-by-line review can miss.

Ask the agent to summarize the final diff in terms of behavior, files, reuse decisions, tests run, and known limitations. Compare that summary with the actual patch; a mismatch is a reason to investigate, not a reason to trust the summary.

Failure modes and how to correct them

Symptom Likely cause Correction
A new utility duplicates an existing helper The request was implemented before repository search, or search used only the user’s wording Ask for symbol, domain-term, and call-site searches; merge or replace the duplicate and add regression tests.
The agent cites a similarly named module that cannot be reused It read the filename but not the contract, callers, or tests Require a behavioral comparison and a concrete rejection reason before allowing new code.
Several instruction files give conflicting rules Project guidance was copied, allowed to become stale, or maintained in multiple places Choose one authoritative location where possible, remove duplicate rules, and update architecture details.
A new test factory appears beside an existing one The agent did not inspect neighboring reference tests Show the relevant tests in the task prompt and require the new case to follow their fixture pattern.
The patch contains unrelated cleanup Scope and completion criteria were not explicit Request a minimal patch, revert unrelated edits, and record optional refactors separately.
The agent keeps proposing a new abstraction Existing code has an unclear owner or awkward API Ask it to trace ownership and present an extension plan; improve the existing boundary if that is the real issue.
A repository rule causes wrong edits The rule contains stale paths, commands, or architectural assumptions Verify the rule against current source and remove details that cannot be maintained accurately.

Prompt templates you can use

Inspection-only prompt

Do not edit yet. Investigate the requested behavior in this repository. Trace the current flow, search for existing implementations, components, utilities, configuration, fixtures, and tests that may already cover it, and read the strongest matches. Report the files and symbols you inspected, the best reuse candidate, any incompatibility, and the smallest change you would make.

Implementation prompt with a reuse gate

Implement the requested behavior within the stated scope. Reuse or extend an existing implementation whenever it fits. Before adding a new helper, component, service, abstraction, or test fixture, list the existing candidates you checked and explain why each is unsuitable. Follow nearby code and test conventions. Do not perform unrelated cleanup. After editing, report the reuse decision, changed files, tests and checks run, and anything not verified.

Diff-review prompt

Review the complete diff for duplicate or unnecessary code. Check every new symbol and file against existing helpers, components, services, fixtures, configuration, and tests. Identify parallel implementations, speculative abstractions, unrelated cleanup, and scope violations. Recommend the smallest corrective edits, and distinguish required fixes from optional refactoring.

Replace general phrases such as “the requested behavior” with the actual feature and acceptance criteria. If you know the relevant package or directory, name it; if you do not, ask the agent to discover it rather than inventing a path.

What this workflow can and cannot guarantee

Search-first instructions, repository context, reference-test review, and diff inspection make duplication easier to detect and less likely to be introduced. They do not prove that a codebase contains no duplicate logic, and they do not guarantee that an agent will understand every architectural boundary. An agent can miss a dynamically registered component, a generated source file, a convention documented outside the repository, or a semantically equivalent implementation with an unexpected name.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The available official guidance from Cursor, Visual Studio Code, and Anthropic describes recommended practices and product use cases; it does not provide a controlled statistic showing how often agents duplicate code or how much a particular rule reduces duplication. Avoid claims of a guaranteed percentage improvement. Keep human review, tests, and ownership decisions in the loop, especially for security-sensitive or public-facing changes.

A practical completion checklist

  • The request and out-of-scope areas are explicit.
  • The current behavior was traced before editing.
  • Repository search covered domain terms, symbols, callers, tests, and configuration.
  • The agent read the strongest existing candidates and reference tests.
  • Reuse, extension, or rejection of each candidate is documented.
  • Any new implementation has a concrete behavioral or compatibility justification.
  • The change follows local architecture, naming, error handling, and test conventions.
  • No duplicate helper, component, fixture, abstraction, or configuration path was added.
  • The diff contains no unrelated cleanup or speculative refactor.
  • Relevant tests and checks ran, and unverified areas are clearly reported.
  • Repository instructions remain accurate, focused, and free of stale duplicates.

Make this checklist part of the agent’s completion report or pull-request template. Repetition in the process is useful; repetition in the code is what you are trying to prevent.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.