Inferensys

Prompt

Code Duplication and DRY Violation Prompt

A practical prompt playbook for using Code Duplication and DRY Violation Prompt in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job-to-be-done, the ideal user, required inputs, and the boundaries where this prompt should not be applied.

This prompt is designed for platform engineering teams and technical leads who need to systematically reduce maintenance burden caused by duplicated logic across a codebase. Its primary job is to analyze a provided diff or set of files, identify instances of copy-paste programming and near-duplicate code blocks, and produce a structured deduplication opportunity list. The output is not just a list of duplicates; it includes concrete abstraction suggestions, such as extracting a shared function, creating a base class, or introducing a utility module, making it directly actionable for a developer planning a refactoring sprint.

To use this prompt effectively, you must provide a well-scoped [INPUT] that contains the source code to be analyzed. This could be a unified diff from a pull request, the contents of several files in a repository, or a specific module. The prompt is most effective when the [CONTEXT] includes the programming language and the team's preferred abstraction patterns (e.g., 'we prefer composition over inheritance' or 'use functional utility libraries'). You should also define an [OUTPUT_SCHEMA] to structure the findings, typically a JSON array of objects, each containing the duplicate locations (file paths and line ranges), a similarity score, the suggested abstraction, and a rationale. Without a strict schema, the model may produce a narrative report that is difficult to integrate into an automated CI/CD pipeline or a project management tool.

This prompt is not a replacement for a dedicated static analysis tool like SonarQube or a specialized clone detector. It should not be used as a gate to block a pull request automatically, as it can generate false positives. A critical constraint is that intentional duplication—such as code kept separate to avoid premature coupling, to meet stringent performance requirements, or to maintain independent deployment lifecycles—must be handled carefully. Your evaluation criteria must include a step for a human reviewer to flag these as 'accepted duplication' to prevent the prompt from driving unnecessary and potentially harmful abstraction. The next step after generating the deduplication list is to feed each high-confidence finding into a follow-up prompt or a manual review process to design the specific refactoring, ensuring behavior is preserved with existing tests.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Code Duplication and DRY Violation Prompt delivers value and where it creates noise or risk.

01

Good Fit: Cross-File Duplication

Use when: reviewing diffs that touch multiple files or modules where copy-paste logic is likely. The prompt excels at finding near-duplicate blocks across file boundaries that human reviewers miss. Guardrail: Provide full file context, not just the diff, so the model can compare implementations accurately.

02

Bad Fit: Intentional Duplication

Avoid when: codebases deliberately duplicate logic for decoupling, performance, or domain boundary reasons. The prompt will flag these as violations. Guardrail: Maintain a team-specific allowlist of intentional duplication patterns and feed it as [CONSTRAINTS] to suppress false positives before they reach the review queue.

03

Required Inputs

Minimum: a diff or file set with at least two files. Optimal: full repository context plus the team's abstraction guidelines. Guardrail: Without repository context, the prompt cannot distinguish between safe duplication and true DRY violations. Always include the abstraction policy in [CONSTRAINTS] to align suggestions with team standards.

04

Operational Risk: Abstraction Cascade

Risk: the prompt may suggest premature abstractions that create tight coupling between unrelated modules. Guardrail: Require human review for any suggested abstraction that spans more than two modules. Add a [CONSTRAINTS] rule that abstraction suggestions must include a coupling risk assessment before implementation.

05

Operational Risk: False Negative on Near-Duplicates

Risk: the prompt may miss semantically identical code that uses different variable names, control structures, or library calls. Guardrail: Pair this prompt with a semantic similarity check in your pipeline. Run the prompt at two diff sizes—narrow and wide—to catch duplication that spans different granularities.

06

Pipeline Integration Point

Best placement: after static analysis but before human review. The prompt adds contextual judgment that linters cannot provide. Guardrail: Never use this prompt as a merge gate. Output should be a deduplication opportunity list for reviewer consideration, not a blocking check. Flag findings as advisory, not mandatory.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for identifying duplicated logic, near-duplicate code blocks, and DRY violations across a diff or file set, producing a deduplication opportunity list with abstraction suggestions.

This prompt template is designed to be copied directly into your AI harness or prompt management system. It accepts a code diff, file set, or repository context and returns a structured analysis of duplication patterns. The square-bracket placeholders allow you to inject the specific code under review, define the output schema your tooling expects, and set constraints that match your team's tolerance for abstraction. Use this template as the foundation for a CI/CD integration, a code review assistant, or a technical debt quantification pipeline.

code
SYSTEM: You are a code duplication and DRY violation detector. Your task is to analyze the provided code and identify duplicated logic, cut-and-paste programming, and near-duplicate code blocks. You must distinguish between intentional duplication (e.g., for performance, clarity, or domain boundary reasons) and unintentional duplication that increases maintenance burden.

INPUT:
[CODE_DIFF_OR_FILE_SET]

CONTEXT:
[PROJECT_CONTEXT]

OUTPUT_SCHEMA:
{
  "findings": [
    {
      "id": "string",
      "severity": "high | medium | low",
      "pattern_type": "exact_duplicate | near_duplicate | structural_duplicate | boilerplate_duplicate",
      "locations": [
        {
          "file": "string",
          "start_line": "integer",
          "end_line": "integer",
          "snippet": "string"
        }
      ],
      "description": "string",
      "abstraction_suggestion": {
        "approach": "extract_function | extract_class | template_method | strategy_pattern | parameterize | configuration_driven",
        "rationale": "string",
        "pseudocode": "string",
        "risk_notes": "string"
      },
      "intentional_duplication_flag": "boolean",
      "intentional_duplication_reason": "string | null"
    }
  ],
  "summary": {
    "total_findings": "integer",
    "high_severity_count": "integer",
    "estimated_maintenance_impact": "high | medium | low",
    "deduplication_effort_estimate": "small | medium | large"
  }
}

CONSTRAINTS:
[CONSTRAINTS]

EXAMPLES:
[FEW_SHOT_EXAMPLES]

INSTRUCTIONS:
1. Analyze the entire input for repeated code patterns, not just identical lines.
2. For each finding, determine if the duplication is likely intentional based on domain context, performance requirements, or framework conventions.
3. Flag intentional duplication clearly and explain why it should not be abstracted.
4. For unintentional duplication, provide a concrete abstraction suggestion with pseudocode.
5. Do not flag duplication that is idiomatic to the language or framework unless it creates a maintenance risk.
6. If [CONSTRAINTS] specifies a severity threshold, suppress findings below that threshold.
7. Output ONLY valid JSON matching the OUTPUT_SCHEMA. No additional text.

To adapt this template for your team, start by defining the [CONSTRAINTS] placeholder. Common constraints include a minimum duplicate block size (e.g., ignore blocks under 5 lines), a severity threshold for reporting, or a list of files and patterns to exclude from analysis. The [PROJECT_CONTEXT] placeholder should include your language, framework, and any domain-specific conventions that help the model distinguish intentional from unintentional duplication. For example, a React project might note that some component structure duplication is idiomatic, while a data processing pipeline might flag any repeated transformation logic. The [FEW_SHOT_EXAMPLES] placeholder is critical for calibration: include 2-3 examples of findings your team considers true positives and 1-2 examples of intentional duplication you want the model to suppress. Without these examples, the model will default to flagging all structural similarity, producing a high false-positive rate that undermines trust in the output.

Before integrating this prompt into a production pipeline, validate the output against a golden dataset of known duplication cases. Test edge cases such as generated code, vendored dependencies, and macro-expanded templates, which often produce structural duplication that should not be refactored. If your team operates in a regulated domain or the code under review controls safety-critical systems, require human review of all high-severity findings before any refactoring is attempted. The intentional_duplication_flag field is your primary defense against false positives—monitor its accuracy in production and use misclassifications to improve your few-shot examples over time.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Code Duplication and DRY Violation Prompt needs to produce a reliable deduplication opportunity list. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[CODE_DIFF_OR_FILE_SET]

The code submission to scan for duplication. Accepts a unified diff, a concatenated file set with paths, or a repository snippet.

diff --git a/src/services/payment.py b/src/services/payment.py @@ -12,6 +12,18 @@ +def validate_card(card):

  • if not card.number:
  • code
       raise ValueError('Missing number')
  • if not card.expiry:
  • code
       raise ValueError('Missing expiry')
  • return True

Must be non-empty. If a diff, ensure file paths are included. If a file set, each block must be preceded by a file path marker. Reject input shorter than 20 lines unless the duplication is trivially absent.

[LANGUAGE]

The primary programming language of the submitted code. Used to select language-idiomatic abstraction suggestions and avoid suggesting patterns that do not exist in the language.

python

Must match one of the supported language tags: python, javascript, typescript, java, go, rust, csharp, ruby, php, kotlin, swift. Reject unknown values with a clear error asking for a supported language.

[DUPLICATION_THRESHOLD]

The minimum number of similar lines or tokens required to flag a block as duplicated. Controls sensitivity.

6

Must be an integer between 3 and 50. Values below 3 produce noise; values above 50 miss near-duplicate functions. Default to 6 if not provided.

[SIMILARITY_STRATEGY]

The comparison strategy: 'exact' for token-identical blocks, 'normalized' for blocks that match after variable renaming and literal normalization, or 'structural' for blocks with the same AST shape.

normalized

Must be one of: exact, normalized, structural. Reject any other value. If structural is chosen, the model must be capable of parsing the [LANGUAGE] AST; otherwise, fall back to normalized.

[CONTEXT_WINDOW_LINES]

The number of surrounding lines to include with each finding for human review context.

5

Must be an integer between 0 and 20. 0 means no context. Values above 20 risk exceeding output token limits when many findings are present. Default to 5.

[MAX_FINDINGS]

The maximum number of deduplication findings to return. Prevents output overload on large codebases.

15

Must be an integer between 1 and 50. The prompt should return the highest-severity findings first when the limit is reached. Default to 15.

[KNOWN_INTENTIONAL_DUPLICATION]

A list of file paths, function names, or block signatures that are known intentional duplicates and should be excluded from findings. Prevents false positives for boilerplate, generated code, or fork points.

['src/generated/proto/', 'config_loader_legacy']

Must be a JSON array of strings. Each string is a substring match against file paths or function names. If null or empty, no exclusions are applied. Validate that the array is well-formed JSON.

[ABSTRACTION_STYLE]

The preferred abstraction style for refactoring suggestions: 'function' for extract-function, 'class' for extract-class or inheritance, 'generic' for generics/templates, or 'mixin' for mixin/trait patterns.

function

Must be one of: function, class, generic, mixin. Reject unknown values. The prompt should fall back to 'function' if the value is missing and the language does not support the requested style.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Code Duplication and DRY Violation Prompt into a CI pipeline, code review tool, or batch analysis workflow.

This prompt is designed to operate on a structured input containing a file set or unified diff, and it expects a machine-readable output schema. The most reliable integration pattern is to call the prompt from a CI job or a code review automation service (such as a GitHub Action, GitLab CI, or a custom pre-commit hook) that can supply the diff context and parse the JSON response. The prompt should be treated as a stateless function: given a set of code changes, it returns a list of duplication findings. Avoid using this prompt interactively in a chat interface for production use; instead, wrap it in an API call with strict timeout, retry, and validation logic.

Before sending the prompt, assemble the [INPUT] by extracting the diff or file contents from the version control system. For pull requests, use the PR's unified diff. For batch repository analysis, chunk the codebase into logical groups (e.g., by module or directory) to stay within context window limits. The [CONSTRAINTS] field should be populated with your team's duplication threshold (e.g., minimum number of duplicated lines, similarity percentage) and any domain-specific patterns to ignore (e.g., boilerplate, license headers, generated code). The [OUTPUT_SCHEMA] should be enforced by the application layer: parse the model's JSON response, validate it against a schema that requires file_path, line_range, duplicate_of, similarity_score, and abstraction_suggestion fields, and reject any response that does not conform. Implement a retry loop with exponential backoff (max 3 attempts) for malformed responses, and log each attempt for observability. For high-risk codebases where a false negative could mask a critical maintenance issue, route findings with a similarity_score above 0.85 to a human review queue before auto-commenting on the PR.

Model choice matters for this task. Use a model with strong code understanding and a large context window, as duplication analysis often requires holding multiple files in context simultaneously. If the diff is too large, pre-filter it using a lightweight syntactic clone detector (e.g., a token-based tool) to identify candidate duplicate regions, then use this prompt only on those candidates to generate the contextual explanation and abstraction suggestion. Always log the prompt version, model identifier, and input hash alongside the output for auditability. Do not use this prompt as a gate that blocks merges automatically; instead, surface findings as non-blocking comments or tickets until the team has calibrated the false positive rate against their codebase norms.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required fields, types, and validation rules for the deduplication opportunity list produced by the Code Duplication and DRY Violation Prompt. Use this contract to parse, validate, and integrate the model's output into your code review pipeline.

Field or ElementType or FormatRequiredValidation Rule

duplication_opportunities

Array of objects

Root key must be an array. Schema check: validate array length >= 0. If no duplication is found, return an empty array, not null.

duplication_opportunities[].id

String (kebab-case)

Unique identifier for the finding. Must match pattern ^dup-[a-z0-9-]+$. Parse check: reject if duplicate IDs exist in the array.

duplication_opportunities[].type

Enum string

Must be one of: exact_duplicate, near_duplicate, structural_duplicate, boilerplate. Schema check: reject any other value.

duplication_opportunities[].primary_location

Object

Must contain file (String) and line_range (String matching ^L\d+-L\d+$). Parse check: validate file path is non-empty.

duplication_opportunities[].duplicate_locations

Array of objects

Each object must have file (String) and line_range (String). Array must contain at least one entry. Schema check: reject if empty.

duplication_opportunities[].abstracted_logic

String or null

A natural language description of the common logic. If the duplication is intentional, set to null. Null allowed: true.

duplication_opportunities[].refactoring_suggestion

String or null

A concrete suggestion for abstraction (e.g., extract function, create base class). Set to null if intentional_duplication is true. Null allowed: conditional on intentional_duplication.

duplication_opportunities[].intentional_duplication

Boolean

Set to true if the duplication appears to be a deliberate design choice (e.g., for decoupling). If true, refactoring_suggestion must be null. Validation rule: cross-field consistency check.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using a Code Duplication and DRY Violation Prompt and how to guard against it in production.

01

False Positives on Intentional Duplication

Risk: The model flags code that is intentionally duplicated for good reasons—forking for divergent business logic, performance-critical inlining, or maintaining isolation between bounded contexts. This erodes trust in the tool. Guardrail: Include a [CONSTRAINTS] block that explicitly lists approved duplication patterns (e.g., 'forked from shared lib for independent release cadence'). Add a post-processing rule that suppresses findings if a commit message or code comment contains a DRY-OK marker.

02

Missing Near-Duplicate Logic

Risk: The prompt only detects exact or syntactically similar blocks but misses semantically identical logic implemented with different variable names, control flow, or library calls. This leaves the most insidious duplication hidden. Guardrail: Instruct the model to compare abstract syntax tree (AST) structures or pseudocode representations rather than raw text. In the eval harness, include test cases where the same algorithm is implemented with different loop styles and assert that they are flagged.

03

Overly Abstract or Unsafe Refactoring Suggestions

Risk: The model proposes a generic abstraction that introduces tight coupling, breaks an existing public API, or ignores critical side effects. A bad abstraction is often worse than duplication. Guardrail: Add a hard rule in the prompt: 'Proposed abstractions must not change the public interface or introduce a new shared dependency without flagging it as a breaking change.' Route all generated refactoring suggestions to a human review queue before they become tickets.

04

Context Window Truncation on Large Diffs

Risk: When analyzing a large diff or multi-file change, the prompt exceeds the context window, causing the model to silently ignore the middle or end of the input. This leads to a high false-negative rate on large PRs. Guardrail: Implement a chunking strategy in the application harness that splits the input by file or logical module boundary. Run the prompt on each chunk independently and then use a second 'merge and deduplicate' prompt to consolidate the findings into a single report.

05

Ignoring Configuration and Infrastructure Duplication

Risk: The prompt is tuned for application code (e.g., Python, Java) and fails to detect dangerous copy-paste across YAML configs, Dockerfiles, or Terraform modules. Guardrail: Explicitly define the [INPUT] schema to accept file-type metadata. Add a specific instruction: 'Analyze all provided file types, including config, IaC, and build scripts, for duplicated blocks. Treat environment-specific variations as potential DRY violations unless marked with a # env-specific comment.'

06

Output Format Drift in Structured Reports

Risk: The model occasionally returns a markdown list instead of the required JSON array of finding objects, or it nests the JSON inside a markdown code block, breaking the CI/CD pipeline parser. Guardrail: Use a strict [OUTPUT_SCHEMA] with a JSON Schema definition. Implement a validation layer in the harness that catches malformed JSON, extracts it from markdown fences if necessary, and retries the prompt with a stern format correction instruction before failing the check.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Code Duplication and DRY Violation Prompt's output before integrating it into a CI pipeline or review workflow. Each criterion includes a pass standard, a failure signal, and a test method.

CriterionPass StandardFailure SignalTest Method

Duplication Detection Accuracy

All identified blocks are functionally or structurally duplicated; no false positives on intentionally distinct code.

Output flags boilerplate, interface implementations, or domain-required repetition as violations.

Manual review of a sample with known intentional duplication (e.g., similar DTOs) to measure false positive rate.

Near-Duplicate Sensitivity

Identifies blocks with high structural similarity but different identifiers/literals, noting the variance.

Misses copy-pasted blocks where only variable names were changed; treats near-duplicates as entirely unique.

Inject a known near-duplicate pair into the test [INPUT] and verify it appears in the output with a similarity note.

Abstraction Suggestion Relevance

Each deduplication opportunity includes a concrete, safe abstraction pattern (e.g., extract method, template, parameterize).

Suggestions are vague ('refactor this'), architecturally inappropriate, or would break existing interfaces.

Check that each suggestion in the output maps to a standard refactoring catalog entry and is scoped to the identified block.

Severity and Impact Ranking

Findings are ranked by maintenance risk (e.g., duplication size, frequency, criticality of module) with clear rationale.

All findings have the same severity or ranking is based on arbitrary factors like line number order.

Verify the output contains a 'severity' or 'priority' field for each finding and that the top-ranked item is the most impactful duplication.

Contextual Explanation Groundedness

Each finding's explanation references specific file paths, line ranges, and the duplicated logic's purpose.

Explanations are generic ('this code is duplicated') without citing exact locations or the functional context.

Parse the output and confirm each finding object has non-null [FILE_PATH] and [LINE_RANGE] fields used in the explanation text.

Intentional Duplication Handling

Output explicitly flags or omits known acceptable duplication patterns (e.g., simple getters/setters, spec files) as low-risk or intentional.

Output recommends deduplicating trivial or structurally necessary code, creating high noise.

Include a test file with standard boilerplate and verify it is either absent from the output or tagged with a low-risk/intentional label.

Output Schema Compliance

Output is valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed.

Output is missing required fields, uses incorrect types, or is wrapped in markdown fences.

Automated JSON Schema validation against the expected [OUTPUT_SCHEMA] definition.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict [OUTPUT_SCHEMA] with JSON fields for finding_id, files, line_ranges, duplication_type (exact/near-duplicate/structural), abstraction_suggestion, and confidence. Include a [CONSTRAINTS] block requiring line-range evidence and a false_positive_risk flag for each finding. Wire the output into a CI check that posts findings as inline review comments.

code
[OUTPUT_SCHEMA]
{
  "findings": [
    {
      "finding_id": "string",
      "files": ["string"],
      "line_ranges": ["string"],
      "duplication_type": "exact | near-duplicate | structural",
      "duplicated_logic_summary": "string",
      "abstraction_suggestion": "string",
      "confidence": 0.0-1.0,
      "false_positive_risk": "low | medium | high",
      "false_positive_rationale": "string"
    }
  ]
}

Watch for

  • Silent format drift where the model drops false_positive_risk on low-confidence findings
  • Missing abstraction_suggestion when duplication is structural rather than literal
  • The model collapsing multiple near-duplicate blocks into a single vague finding
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.