33 AI Prompts for Refactoring

The best Refactoring prompts in the Coding library. Tested on ChatGPT, Claude, Gemini and every major model.

Browse the prompts

## Role
You are a senior software engineer specializing in code quality audits, refactoring strategy, and technical debt prevention across production systems.

## Task
Perform a comprehensive code quality audit and deliver actionable refactoring recommendations organized into five analysis areas:

1. **Refactoring for Clarity** – identify code smells, duplication, complexity hotspots, and structural improvements
2. **Configuration & Secrets** – flag hardcoded values, credentials, and environment-specific logic that should be externalized
3. **Dependency Review** – assess libraries for security vulnerabilities, licensing issues, version conflicts, and performance impact
4. **Automated Quality Gates** – recommend linting rules, pre-commit hooks, CI pipeline checks, and coverage thresholds
5. **Documentation** – provide templates for README, API contracts, architecture decision records, and

Code Quality Audit and Refactoring Recommendations

Generates a five-part code quality audit covering refactoring opportunities, configuration issues, dependency risks, automated quality gates, and documentation templates. Runs on ChatGPT, Claude, Gemini, and Grok.

151
## Role
You are a code simplification specialist who transforms verbose, overly-defensive code into clear, maintainable scripts. You identify redundant checks, consolidate repeated patterns, and express logic in its simplest human-readable form while preserving exact functionality.

## Task
Analyze the provided script and produce a simplified version that eliminates unnecessary complexity without breaking behavior.

1. **Analyze** the script's purpose and logical flow to identify:
   - Redundant conditional checks and defensive programming
   - Repeated code blocks that can be consolidated
   - Overly complex expressions that obscure intent
   - Unnecessary intermediate variables

2. **Simplify** by applying these criteria:
   - Prioritize human readability over clever one-liners
   - Remove redundant null/undefined checks where logic guarantees values
   - Consolidate multiple similar c

Code Simplification and Refactoring Prompt

Transforms verbose, overly-defensive code into clear, maintainable scripts by eliminating redundant checks, consolidating patterns, and improving readability while preserving functionality. Runs on ChatGPT, Claude, and Cursor.

113

Dead Code Audit and Cleanup Roadmap Prompt

Runs a three-phase dead-code audit that distinguishes genuinely unused code from framework-invoked symbols, produces a risk-ranked findings table, and generates a sequenced cleanup roadmap with LOC and build-time estimates. Built for ChatGPT, Claude, and Gemini.

100

Eliminate Redundant Code Refactoring Prompt

Identifies and removes code duplication, dead code, and unnecessary abstractions using Martin Fowler's refactoring principles. Runs on ChatGPT, Claude, Gemini, and Grok to produce a prioritized consolidation plan with before/after snippets and implementation steps.

92

Analyze Design Architecture With Domain-Driven Design

Generates a comprehensive modular architecture plan that restructures monolithic codebases into domain-centric systems using DDD principles. Runs on ChatGPT, Claude, Gemini, and Grok to map bounded contexts, aggregate roots, and migration strategies.

66
## Role

You are an expert code refactoring consultant specializing in identifying code smells and applying proven refactoring patterns from Martin Fowler's catalog to transform problematic code into maintainable, elegant solutions.

## Task

Analyze the provided code, identify specific code smells, prioritize issues by severity and impact, then guide the user through incremental refactoring transformations while ensuring behavior preservation.

## Context

**Code to refactor:**
```
{{code}}
```

**Project context:** {{project-context}}

## Process

### 1. Code Analysis & Smell Detection

Examine the code for common smells including:
- Long Methods, Large Classes, Duplicate Code
- Feature Envy, Data Clumps, Primitive Obsession
- Switch Statements, Message Chains, Middle Man
- Inappropriate Intimacy, Lazy Class, Speculative Generality
- Data Class, Refused Bequest, Temporary Field
- Paral

Fix Problematic Code Refactoring Prompt

Analyzes code for smells and applies Martin Fowler refactoring patterns through incremental, behavior-preserving transformations. Runs on ChatGPT, Claude, and Cursor to produce step-by-step refactoring roadmaps and clean code.

66
## Role
You are an expert software refactoring specialist applying Martin Fowler's techniques: improve code structure without altering functionality, use small controlled steps, eliminate duplication, clarify intentions through naming, and break complex units into understandable pieces.

## Task
Systematically refactor the provided code to improve structure, readability, and maintainability while preserving exact behavior.

## Context
{{code-and-context}}

Include:
- The code to refactor
- Programming language
- What the code does
- Specific concerns or confusing elements
- Any testing constraints

## Process
1. **Analyze** the code to identify its core purpose and functionality
2. **Catalog** confusing, duplicated, or poorly structured elements
3. **Apply** refactoring techniques: Extract Method, Rename Variable, Remove Duplication, Simplify Conditional Expressions
4. **Rewrite** proble

Code Refactoring Prompt for ChatGPT and Claude

Generates structured refactorings that improve code readability and maintainability while preserving exact behavior, using Martin Fowler's proven techniques. Runs on ChatGPT, Claude, and Cursor.

63

Analyze Class Structure for SOLID Principles

Analyzes class code to identify Single Responsibility Principle violations and provides concrete refactoring recommendations following SOLID principles. Runs on ChatGPT, Claude, Gemini, and Grok with before/after code examples in any programming language.

61

Code Simplification and Refactoring Prompt

Generates multi-phase refactoring plans that transform complex, convoluted code into maintainable solutions by identifying DRY violations, naming issues, and over-complicated logic. Runs on ChatGPT, Claude, and Cursor with before/after comparisons and readability metrics.

61
## Role

You are an algorithm optimization specialist with competitive programming experience and production systems expertise. You diagnose performance bottlenecks caused by suboptimal data structure choices and recommend alternatives grounded in complexity analysis, operation patterns, and real-world constraints.

## Task

Analyze the provided code and operational context, then recommend optimal data structures that balance performance across all operations while accounting for memory, concurrency, and scaling requirements.

## Context

{{system-context}}

Include:
- Current data structure implementations (code snippets)
- Operation frequencies (inserts/deletes/searches/updates per second)
- Data characteristics (size, type, distribution)
- Performance constraints (latency/throughput requirements)
- System limits (memory budget, concurrency model, thread-safety needs)

## Analysis Meth

Data Structure Optimization Prompt for Performance

Analyzes code and operational context to recommend optimal data structures based on complexity analysis, operation frequencies, and real-world constraints. Runs on ChatGPT, Claude, Gemini, and Grok.

51
## Role

You are an expert software architect specializing in code refactoring, cyclomatic complexity reduction, and transforming complex conditional logic into maintainable code structures following Steve McConnell's "Code Complete" principles.

## Task

Analyze the provided conditional code and deliver comprehensive refactoring recommendations that improve readability, testability, and maintainability through design patterns and structural improvements.

## Context

Language: {{language}}

Code to refactor:
```
{{code-to-refactor}}
```

Constraints: {{constraints}}

## Process

1. **Complexity Analysis**: Identify all conditional branches, nested structures, and hotspots. Calculate current cyclomatic complexity and pinpoint specific pain points.

2. **Refactoring Strategy**: Apply proven techniques systematically:
   - Guard clauses to eliminate deep nesting
   - Lookup tables for comp

Refactor Complex Conditional Logic Code Prompt

Generates detailed refactoring strategies and before-and-after code examples that reduce cyclomatic complexity in nested conditionals. Runs on ChatGPT, Claude, and Cursor to transform tangled logic into maintainable structures following Code Complete principles.

50

Detect Duplicate Functions in Code

Identifies duplicate and similar functions across a codebase, calculates similarity scores using cyclomatic complexity and structural patterns, and proposes DRY refactoring strategies with before/after examples. Runs on ChatGPT, Claude, and Cursor.

49

Refactor Plan in Independent Batches

Generate a structured refactoring plan and incremental execution strategy to refactor a software module to a new architectural pattern.

49

Loop Optimization Analysis Prompt for Code Refactoring

Analyzes loop-heavy code and generates concrete optimization transformations with performance estimates. Runs on ChatGPT, Claude, and other text models to identify algorithmic improvements, memory access patterns, and micro-optimizations.

49
## Role

You are an expert software architect specializing in code cohesion analysis and refactoring. You use LCOM (Lack of Cohesion of Methods) metrics to identify architectural decay and guide surgical refactoring that improves maintainability without breaking existing functionality.

## Task

Analyze the provided code to calculate cohesion metrics, identify classes doing too much, and provide a concrete refactoring plan that splits low-cohesion classes into focused, single-responsibility units.

## Context

The codebase suffers from architectural decay—monolithic classes where unrelated methods coexist, making testing difficult and causing cascading bugs with every change. Technical debt is compounding and velocity is declining.

{{code-to-analyze}}

{{constraints}}

## Analysis Method

- Calculate LCOM using the Lethbridge and Laganière formula: LCOM = |P| - |Q| if |P| > |Q|, otherwi

Analyze Code Cohesion

Generates LCOM-based cohesion analysis and refactoring plans to split monolithic classes into single-responsibility units. Runs on ChatGPT, Claude, Gemini, and Grok for text-based code analysis.

48
## Role

You are a regex optimization specialist analyzing patterns for performance bottlenecks and backtracking issues.

## Task

Analyze the provided regex pattern and deliver actionable optimizations:

1. **Pattern Analysis**: Examine structure character by character, identifying nested quantifiers, alternations, and lookarounds that trigger excessive backtracking.

2. **Backtracking Visualization**: Trace the regex engine's decision tree on the sample input, showing where and why catastrophic backtracking occurs.

3. **Performance Diagnosis**: Identify specific anti-patterns (e.g., `(a+)+`, `(a*)*`) causing exponential complexity and explain the computational cost.

4. **Atomic Solutions**: Recommend possessive quantifiers (`++`, `*+`, `?+`) and atomic groups (`(?>...)`) to prevent backtracking, explaining how each modification changes engine behavior.

5. **Pattern Restructuring**: 

Optimize Regex Performance

Analyzes regular expression patterns to identify and eliminate catastrophic backtracking, then delivers optimized alternatives with linear time complexity. Runs on ChatGPT, Claude, Gemini, and Grok.

47

Compare Two Code Versions

Generates a structured, multi-phase analysis comparing two code versions across design patterns, complexity metrics, performance trade-offs, and maintainability. Runs on ChatGPT, Claude, Gemini, and Grok.

46

Clarify Unclear Code Prompt for ChatGPT

Generates a multi-phase refactoring plan that transforms unclear code into self-documenting, readable code following Clean Code principles. Runs on ChatGPT, Claude, and Cursor with before/after comparisons at each step.

46
## Role

You are a code optimization specialist focused on ES6 module analysis and tree-shaking. Your expertise lies in identifying unused imports, distinguishing runtime from type-only dependencies, and maximizing bundle efficiency through static analysis.

## Task

Analyze the provided codebase to identify and eliminate unused imports. Use tree-shaking principles to reduce bundle size while maintaining type safety and runtime functionality.

**Analysis workflow:**
1. Parse all import statements and categorize by type (named, default, namespace, side-effect)
2. Trace actual usage of each imported identifier throughout the codebase
3. Distinguish runtime imports from type-only, side-effect, and mixed-use imports
4. Identify tree-shaking blockers (wildcard imports, dynamic imports, re-exports)
5. Generate actionable refactoring recommendations

## Context

{{codebase-files}}

**Environmen

Eliminate Unused Imports Code Refactoring Prompt

Analyzes JavaScript and TypeScript codebases to identify and remove unused imports, optimize tree-shaking, and reduce bundle size. Runs on ChatGPT, Claude, and Cursor for ES6 module optimization.

46
## Role

You are a file I/O performance optimization specialist. Apply techniques from *The Linux Programming Interface* by Michael Kerrisk, focusing on buffer mechanics, memory-mapped files, asynchronous operations, and system call reduction.

## Task

Analyze the provided file handling code and system context to identify I/O inefficiencies, then deliver targeted optimization strategies that reduce system call overhead and resource contention.

## Context

{{code-and-system-context}}

Include in your input:
- Current file handling code
- File sizes and access patterns (sequential, random, or mixed)
- Performance requirements (latency and throughput targets)
- System constraints (memory, CPU, disk limits)

## Output

### Current I/O Performance Analysis

Identify inefficient patterns such as:
- Excessive system calls from unbuffered operations
- Misaligned buffer sizes causing partial re

File I/O Performance Optimization Prompt

Analyzes file handling code and applies Linux system-level techniques to reduce I/O bottlenecks, minimize system call overhead, and improve throughput. Runs on ChatGPT, Claude, and other text-generation models.

45

Python Memory Usage Optimization Prompt

Generates a multi-phase memory optimization plan for Python applications, analyzing memory patterns, profiling allocation hotspots, and recommending data structure replacements. Runs on ChatGPT, Claude, Gemini, and Grok.

41

Recommend Codebase Naming Conventions

Generates structured naming convention guidelines for variables, functions, classes, and tests based on Clean Code principles. Analyzes your code context and runs on ChatGPT, Claude, Gemini, or Grok.

41

Detect Inefficient Recursion

Analyzes recursive functions for performance bottlenecks and generates tail-call optimization, iterative transformations, memoization, and dynamic programming solutions. Runs on ChatGPT, Claude, and Cursor to produce optimized code with complexity comparisons.

41
## Role

You are an expert software architect and refactoring specialist with deep knowledge of Martin Fowler's refactoring catalog and extensive experience transforming legacy codebases into maintainable, elegant systems.

## Task

Systematically analyze the provided code for improvement opportunities and deliver specific refactoring recommendations with detailed before-and-after examples that enhance maintainability, readability, and performance without altering functionality.

## Context

{{code-and-context}}

Provide the code to analyze, the programming language, your primary concerns (e.g., complexity, duplication, testability), team experience level with refactoring, and any relevant time, budget, or technical constraints.

## Analysis Process

1. Scan for common code smells: long methods, large classes, duplicate code, feature envy, data clumps, primitive obsession, inappropriate 

Analyze Code Smells

Generates a systematic refactoring plan that identifies code smells and delivers specific before-and-after examples with techniques from Martin Fowler's catalog. Runs on ChatGPT, Claude, and other text models.

41

What are AI prompts for Refactoring?

AI prompts for Refactoring are engineered instructions that already work. These are not one-line questions. Each one fixes the role, the context, the task and the output format before you type a word, so you get a usable result on the first run instead of the fourth.

They cover the work Refactoring actually get asked for: research and briefs, copy and content, analysis and reporting, planning, outreach and the admin that eats the day. Open a card to see the full prompt and the output it returns.

Popular on this page right now: "Code Quality Audit and Refactoring Recommendations", "Code Simplification and Refactoring Prompt", "Dead Code Audit and Cleanup Roadmap Prompt".

33 on this page, every one scoped to Refactoring. Free to read, free to copy.

Why these prompts work for Refactoring

A weak prompt costs you the hour you were trying to save: you rewrite it three times, get something generic, then finish the job by hand. An engineered prompt front-loads that thinking once.

In Refactoring that means first drafts you can send, analysis you can act on, and the repetitive work handed off, so the time goes into judgement instead of typing.

Every prompt here was written for a real job and tested against the models people actually use. Nothing scraped from a thread.

How to use these prompts

Open a prompt, copy it, and replace the [bracketed] variables with your own product, audience or topic. The structure around them stays as is. That structure is the part doing the work.

Paste it into ChatGPT, Claude, Gemini, Grok or the model you already use. If the output drifts, tighten the context line instead of rewriting the whole prompt.

No account needed to copy one. No setup, no extension, nothing to install.

Which AI tool works best for Refactoring prompts?

Text prompts here run well in ChatGPT, Claude, Gemini and Grok; image prompts target Midjourney and Nano Banana. Each card lists the models it was tested with.

Are these AI prompts free to use?

A big part of the library is free: open a prompt, copy it, use it. Premium packs and the Complete AI Bundle unlock the full collection with lifetime updates.

How do I adapt these prompts to my use case?

Start with the [variables]: niche, audience, constraints. If the result still misses, add one example of the output you want. A single good example beats three extra instructions.

For a prompt built from scratch, the Start Now card above opens the custom prompt generator.

Related resources

Get smarter on AI every week

One email a week with the best new prompts, tools, and model updates. Unsubscribe anytime.

Join 100,000+ subscribers. One email a week, real prompts, tools, and model updates. Unsubscribe anytime.

About Refactoring prompts

Refactoring prompts improve code without changing what it does: extract a function, split a large file, remove duplication, rename for clarity, replace a nested conditional with a clearer structure, migrate a module to a newer pattern. Each prompt starts by asking the model to describe the current behaviour and the tests that cover it, then makes the change in small steps with the behaviour preserved, and ends with a diff you can read.

Developers use them on the files everyone avoids touching. Tech leads use the assessment prompts to decide what to refactor first. The prompts refuse to refactor code without tests and offer to write characterisation tests first, which is the discipline that keeps a refactor from becoming a rewrite. Run them one file at a time; a refactor across a whole project in one prompt produces changes nobody can review.