Coding
AI Prompt for Removing Duplication
Eliminate code duplication with this AI prompt: find the shared core, extract a parameterized abstraction, and keep each caller's behavior intact.
The prompt
Role: You are a refactoring expert who eliminates duplication with the RIGHT abstraction — not the first one that comes to mind. Context: Language: [LANGUAGE]. The duplicated code: [CODE_COPIES]. Scope: [SCOPE]. Task: 1) Identify what is truly common vs what varies between the copies. 2) Propose the abstraction (function with parameters, strategy, template method, config-driven — choose the simplest that fits) and JUSTIFY why this shape and not a simpler/duplicated alternative. 3) Show the refactored code: the abstraction plus all call sites updated. 4) Verify: explain how each original copy's behavior is preserved. 5) Warn where abstraction would be WRONG — copies that look similar but represent different concepts. Format: Common-vs-varying analysis, then the proposed abstraction with justification, then refactored code, then the behavior verification, then the do-not-abstract warning. Constraints: Follow the Rule of Three — do not abstract two slightly-similar copies prematurely. The abstraction must be simpler to understand than the duplication it replaces.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [CODE_COPIES] [SCOPE]
Example input
LANGUAGE=JavaScript, CODE=3 near-identical form-validation blocks for login, signup, checkout, STRATEGY=shared validator with config, SCOPE=these 3 only
How to use this prompt
Show all the copies — the AI needs to see the variations to design the right abstraction. Scope the refactor; 'all duplication everywhere' is a trap.
Tips for the best results
- Ask 'what varies' first — the varying parts design the parameters.
- Heed the do-not-abstract warning; wrong abstractions are worse than duplication.
- After refactoring, ask for a test proving all original behaviors still hold.
Frequently asked questions
What if the copies differ slightly?
It extracts the shared core and parameterizes the differences — then warns you where the copies have already diverged.
What is the Rule of Three?
Wait for three duplications before abstracting. Two similar copies often diverge; the third reveals the true common shape. The prompt enforces this discipline.