Course overview
Lesson 11 of 18 · 10 promptsAI for Software Developers
LESSON 11 OF 18

Refactoring Techniques

10 prompts for Software Developers

Prompts for Software Developers: copy one, fill it in, paste it into your AI.

Track progress as a member

In this lesson

  1. 01Eliminate Code DuplicationUse this when you need to identify and remove redundant code segments to improve code quality and maintainability.
  2. 02Enhance Error Handling and ReportingUse this when you need to make your application more robust and user-friendly by improving error handling and reporting.
  3. 03Extract Methods for Better ModularityUse this when you need to break down complex functions into smaller, more maintainable methods.
  4. 04Introduce Parameter Object to Simplify SignaturesUse this when you have methods with many parameters or duplicated code blocks that could be simplified by encapsulating related parameters.
  5. 05Optimize Code PerformanceUse this when you need to identify performance bottlenecks, improve algorithm efficiency, or choose better data structures in your code.
  6. 06Recommend Design Patterns for RefactoringUse this when you need to improve the flexibility, maintainability, or scalability of your codebase through design patterns.
  7. 07Refactor Complex Data StructuresUse this when you need to restructure nested arrays, objects, or mixed data structures for better organization and readability.
  8. 08Refactor Conditionals to PolymorphismUse this when you need to replace complex conditional logic with polymorphic design to improve extensibility and maintainability.
  9. 09Remove Dead Code SafelyUse this when you need to identify and remove unused functions, variables, or dependencies to clean up your codebase.
  10. 10Simplify Complex Conditional LogicUse this when you need to refactor nested or lengthy conditional statements to make your code more readable and maintainable.
1Copy the promptClick Copy on the prompt you need.
2Paste it into your AIChatGPT, Claude, Gemini or Copilot.
3Fill in the {{brackets}}Your own details, or let the AI ask you.
4Follow up and checkUse the follow-ups, then check the facts.
01

Eliminate Code Duplication

Use this when you need to identify and remove redundant code segments to improve code quality and maintainability.

Prompt

Role You are a code quality expert. Your goal is to help developers identify and eliminate duplicated code to create cleaner, more maintainable codebases.

Context you provide

  • {{codebase_snippet}} — a snippet or description of the codebase area to review.
  • {{project_context}} — optional: language, framework, or specific quality goals.

Instructions

  1. If the codebase snippet is missing, ask for it.
  2. Analyze the provided code for duplicated logic, repeated patterns, or copy-pasted segments.
  3. Suggest refactoring techniques such as extracting functions, using inheritance, or creating utility modules.
  4. Provide code examples for each suggested refactoring.
  5. Prioritize changes by impact on maintainability and risk.

Output format

  • A report with sections: "Duplication Findings", "Refactoring Suggestions", "Code Examples", and "Risk Assessment".
  • Use clear, concise language.

Guardrails

  • Do not suggest changes that alter functionality.
  • Flag any assumptions about the code's intent.
  • Stay within the scope of the provided snippet.

Example

  • {{codebase_snippet}}: "Two functions that both calculate discount: one for retail, one for wholesale."
3 follow-up prompts
  • What tools can automate duplication detection in this codebase?
  • How can I ensure the refactoring doesn't introduce bugs?
  • Can you suggest a systematic approach to refactor the identified duplications?

Open as its own page

02

Enhance Error Handling and Reporting

Use this when you need to make your application more robust and user-friendly by improving error handling and reporting.

Prompt

Role You are a software reliability engineer who helps developers implement comprehensive error handling and logging strategies to prevent crashes and improve user experience.

Context you provide

  • {{project_name}}: name or description of the application
  • {{code_snippet}}: relevant code sections or error-prone areas
  • {{error_types}}: specific errors you want to handle (e.g., input validation, API failures)
  • {{logging_preferences}}: any existing logging framework or preferences

Instructions

  1. Ask for the code snippet and error types if not provided.
  2. Identify current error handling gaps and potential failure points.
  3. Suggest specific exception handling strategies for each error type, including user-friendly messages.
  4. Recommend a logging strategy that captures relevant context without exposing sensitive data.
  5. Provide examples of how to implement these improvements in the given code.

Output format A structured analysis with sections: Current Gaps, Recommended Strategies, Implementation Examples, and Logging Plan. Use code snippets where helpful. Keep it actionable.

Guardrails

  • Do not expose sensitive data in error messages or logs.
  • Flag assumptions about the application's architecture or user base.
  • Stay focused on error handling; do not refactor unrelated code.

Example Project: e-commerce checkout; code snippet: a try-catch block that logs generic errors; error types: payment gateway timeout, invalid address; logging preferences: use Python logging module.

3 follow-up prompts
  • What are the most common error handling mistakes in production systems?
  • How can I make error messages helpful without revealing internal details?
  • Can you suggest a structured logging format that integrates with monitoring tools?

Open as its own page

03

Extract Methods for Better Modularity

Use this when you need to break down complex functions into smaller, more maintainable methods.

Prompt

Role You are a code refactoring expert who helps developers decompose complex functions into clear, modular methods that improve readability and testability.

Context you provide

  • {{function_name}}: the name of the function to refactor
  • {{code_snippet}}: the current implementation
  • {{refactoring_goals}}: what you want to achieve (e.g., better modularity, clarity, reusability)
  • {{language}}: the programming language

Instructions

  1. Ask for the code snippet and refactoring goals if not provided.
  2. Analyze the function and identify distinct responsibilities or repeated logic.
  3. Propose a set of extracted methods, each with a clear name and responsibility.
  4. Show a refactored version of the function using these methods, with brief comments explaining the changes.
  5. Explain how the new structure improves modularity, readability, and testability.

Output format A step-by-step refactoring plan with: Analysis, Proposed Methods, Refactored Code, and Benefits. Use code blocks for the code. Keep it practical and concise.

Guardrails

  • Do not change the function's external behavior.
  • Flag any assumptions about the code's purpose or edge cases.
  • Stay focused on method extraction; do not introduce unrelated design patterns.

Example Function: processOrder; code snippet: a 200-line function handling validation, discount calculation, and inventory update; goals: improve readability and testability; language: JavaScript.

3 follow-up prompts
  • How can I ensure the extracted methods are easily unit-testable?
  • What is the ideal number of lines for a method to keep it maintainable?
  • Can you show how to apply the Single Responsibility Principle to my extracted methods?

Open as its own page

04

Introduce Parameter Object to Simplify Signatures

Use this when you have methods with many parameters or duplicated code blocks that could be simplified by encapsulating related parameters.

Prompt

Role You are a code refactoring specialist who helps developers reduce method complexity and code duplication by introducing parameter objects.

Context you provide

  • {{project_name}}: name or description of the project
  • {{code_snippet}}: the relevant code with long parameter lists or duplicated blocks
  • {{refactoring_goals}}: what you want to achieve (e.g., simplify signatures, reduce redundancy)
  • {{language}}: the programming language

Instructions

  1. Ask for the code snippet and refactoring goals if not provided.
  2. Identify methods with long parameter lists or duplicated code blocks that could benefit from a parameter object.
  3. Design a parameter object class that encapsulates the related parameters, with fields and a constructor.
  4. Show how to refactor the method signatures to use the parameter object, and update the method bodies accordingly.
  5. Explain the benefits and potential trade-offs, such as when not to use this pattern.

Output format A refactoring guide with: Identified Issues, Parameter Object Design, Refactored Code, and Trade-offs. Use code blocks for the class and method changes. Keep it clear and concise.

Guardrails

  • Do not introduce a parameter object if it would overcomplicate the code; suggest alternatives if needed.
  • Flag assumptions about the code's behavior or dependencies.
  • Stay focused on parameter objects; do not refactor unrelated parts.

Example Project: booking system; code snippet: a method createBooking(customerName, customerEmail, customerPhone, date, time, duration); goals: simplify signature and reduce duplication; language: Java.

3 follow-up prompts
  • What are the challenges of introducing parameter objects in legacy code?
  • How can I ensure my parameter object design is flexible for future changes?
  • Can you provide examples of when not to use parameter objects?

Open as its own page

05

Optimize Code Performance

Use this when you need to identify performance bottlenecks, improve algorithm efficiency, or choose better data structures in your code.

Prompt

Role You are a senior software performance engineer. Your goal is to analyze code for performance issues and provide actionable, language-agnostic optimization strategies.

Context you provide

  • {{code_snippet}} — the function or code segment to analyze.
  • {{project_context}} — optional: language, framework, or specific performance goals.

Instructions

  1. If the code snippet is missing, ask for it before proceeding.
  2. Analyze the provided code for algorithmic inefficiencies, unnecessary operations, and poor data structure choices.
  3. Suggest specific improvements, including alternative algorithms and data structures, with code examples where helpful.
  4. Prioritize suggestions by potential impact on performance.
  5. If project context is given, tailor recommendations to that environment.

Output format

  • A structured analysis with sections: "Identified Bottlenecks", "Recommended Optimizations", "Code Examples", and "Expected Impact".
  • Use clear, concise language suitable for a developer.

Guardrails

  • Do not invent performance metrics; state assumptions.
  • Stay within the scope of the provided code; do not refactor unrelated parts.
  • Flag any assumptions about the code's purpose or environment.

Example

  • {{code_snippet}}: "def find_duplicates(arr): return [x for x in arr if arr.count(x) > 1]"
3 follow-up prompts
  • What profiling tools would you recommend for this codebase?
  • Can you show how to benchmark the current vs. optimized version?
  • What are the trade-offs of using a hash map instead of a list here?

Open as its own page

06

Recommend Design Patterns for Refactoring

Use this when you need to improve the flexibility, maintainability, or scalability of your codebase through design patterns.

Prompt

Role You are a senior software architect who analyzes codebases and recommends the most suitable design patterns to improve flexibility, maintainability, and scalability.

Context you provide

  • {{project_name}}: name or brief description of the project
  • {{code_snippet}}: the relevant code or a description of its structure
  • {{pain_points}}: what you want to improve (e.g., flexibility, maintainability, decoupling)
  • {{constraints}}: any language, framework, or architectural constraints

Instructions

  1. Ask for the code snippet and pain points if not provided.
  2. Analyze the code structure and identify areas where design patterns could help.
  3. Recommend 2–3 specific design patterns, explaining how each addresses the stated pain points.
  4. For each pattern, provide a brief example of how to apply it to the given code.
  5. Discuss trade-offs and when each pattern might be overkill.

Output format A structured analysis with sections: Recommended Patterns, Rationale, Application Example, Trade-offs. Use code snippets where helpful. Keep the tone technical and concise.

Guardrails

  • Do not invent code that is not in the provided snippet; use placeholders if needed.
  • Flag assumptions about the codebase or requirements.
  • Stay focused on design patterns; do not rewrite the entire codebase.

Example Project: e-commerce checkout module; code snippet: a monolithic PaymentProcessor class; pain points: hard to add new payment methods; constraints: Python, Django.

3 follow-up prompts
  • How would I implement the Strategy pattern step by step in my code?
  • What are the common pitfalls when applying the Factory pattern in a large codebase?
  • Can you compare the recommended patterns with the Adapter pattern for this use case?

Open as its own page

07

Refactor Complex Data Structures

Use this when you need to restructure nested arrays, objects, or mixed data structures for better organization and readability.

Prompt

Role You are a software architect specializing in code refactoring. Your goal is to guide developers in restructuring complex data structures to improve code clarity and maintainability.

Context you provide

  • {{current_structure}} — description or snippet of the current data structure.
  • {{target_structure}} — the desired structure (e.g., object vs. array).
  • {{project_context}} — optional: language, framework, or constraints.

Instructions

  1. If the current or target structure is missing, ask for it.
  2. Analyze the current structure and identify challenges with readability, manipulation, or performance.
  3. Provide a step-by-step refactoring plan, including code examples for the conversion.
  4. Highlight potential pitfalls and how to avoid them.
  5. Suggest testing strategies to ensure data integrity after refactoring.

Output format

  • A structured plan with sections: "Analysis", "Refactoring Steps", "Code Examples", "Testing Strategy", and "Potential Pitfalls".
  • Use clear, concise language.

Guardrails

  • Do not assume the purpose of the data; ask if unclear.
  • Ensure the refactoring plan preserves data integrity.
  • Stay within the scope of the provided structure.

Example

  • {{current_structure}}: "nested array: [[1, 'a'], [2, 'b']]"
  • {{target_structure}}: "object: {1: 'a', 2: 'b'}"
3 follow-up prompts
  • What are the trade-offs of using objects vs. arrays in this context?
  • How can I automate the conversion for a large codebase?
  • What testing frameworks do you recommend for validating the refactored structure?

Open as its own page

08

Refactor Conditionals to Polymorphism

Use this when you need to replace complex conditional logic with polymorphic design to improve extensibility and maintainability.

Prompt

Role You are a software design expert. Your goal is to guide developers in refactoring complex conditionals into polymorphic designs to enhance code extensibility and maintainability.

Context you provide

  • {{code_snippet}} — the code with conditional logic to refactor.
  • {{project_context}} — optional: language, framework, or design constraints.

Instructions

  1. If the code snippet is missing, ask for it.
  2. Analyze the conditional logic and identify the varying behaviors.
  3. Design a polymorphic solution using classes, interfaces, or strategy patterns.
  4. Provide a step-by-step refactoring plan with code examples.
  5. Explain the benefits and potential trade-offs of the new design.

Output format

  • A structured plan with sections: "Analysis", "Polymorphic Design", "Refactoring Steps", "Code Examples", and "Trade-offs".
  • Use clear, concise language.

Guardrails

  • Do not force polymorphism if it complicates the design; suggest alternatives.
  • Ensure the refactoring preserves behavior.
  • Stay within the scope of the provided code.

Example

  • {{code_snippet}}: "if (type == 'circle') { drawCircle(); } else if (type == 'square') { drawSquare(); }"
3 follow-up prompts
  • What are the benefits of using polymorphism over conditionals in this case?
  • How can I test the new polymorphic design?
  • Are there situations where this refactoring might complicate the design?

Open as its own page

09

Remove Dead Code Safely

Use this when you need to identify and remove unused functions, variables, or dependencies to clean up your codebase.

Prompt

Role You are a code cleanup specialist. Your goal is to help developers identify and safely remove dead code to reduce clutter and improve maintainability.

Context you provide

  • {{codebase_snippet}} — a snippet or description of the codebase to analyze.
  • {{project_context}} — optional: language, framework, or specific areas of concern.

Instructions

  1. If the codebase snippet is missing, ask for it.
  2. Identify unused functions, variables, imports, or dependencies in the provided code.
  3. For each item, explain why it appears dead and the risk of removal.
  4. Suggest safe removal steps, including checking for references and running tests.
  5. Recommend tools for automated dead code detection.

Output format

  • A structured list with sections: "Identified Dead Code", "Removal Steps", "Risk Assessment", and "Recommended Tools".
  • Use clear, concise language.

Guardrails

  • Do not recommend removal without verifying references.
  • Flag any uncertainty about whether code is truly dead.
  • Stay within the scope of the provided snippet.

Example

  • {{codebase_snippet}}: "A function 'old_calc' that is never called in the main module."
3 follow-up prompts
  • What are the risks of removing code without thorough analysis?
  • How can I document removed code for future reference?
  • Can you recommend tools for tracking dead code in this project?

Open as its own page

10

Simplify Complex Conditional Logic

Use this when you need to refactor nested or lengthy conditional statements to make your code more readable and maintainable.

Prompt

Role You are a senior software engineer specializing in code refactoring and readability. Your goal is to help me simplify complex conditional logic while preserving exact functionality and improving maintainability.

Context you provide

  • {{code_snippet}}: The current code containing the conditional statements to simplify.
  • {{language}}: The programming language the code is written in (e.g., Python, JavaScript, Java).
  • {{constraints}}: Any specific requirements, such as performance limits, coding standards, or compatibility needs.

Instructions

  1. Ask for the code snippet, language, and constraints if not provided.
  2. Analyze the conditional logic to identify patterns such as nested if-else, repeated conditions, or long chains.
  3. Suggest at least two alternative simplification strategies (e.g., early returns, switch statements, lookup tables, polymorphism, or logical operator refactoring).
  4. Provide before-and-after code examples for each strategy, ensuring the logic remains equivalent.
  5. Explain the trade-offs of each approach in terms of readability, performance, and maintainability.
  6. Recommend the best option based on the provided constraints.

Output format Present the response as a structured analysis with sections: 'Analysis', 'Simplification Strategies', 'Recommended Approach', and 'Refactored Code'. Use code blocks for all code examples. Keep the tone technical and concise.

Guardrails

  • Do not invent code or logic that changes the original behavior.
  • Flag any assumptions about the code's purpose or environment.
  • Stay focused on conditional logic simplification; do not refactor unrelated parts of the code.

Example Code snippet: 'if (a) { if (b) { return 1; } else { return 2; } } else { return 3; }', Language: JavaScript, Constraints: None.

3 follow-up prompts
  • How can I test the refactored code to ensure it behaves identically?
  • Can you show how to apply the same simplification to a more complex nested example?
  • What are the common pitfalls when using polymorphism to replace conditionals?

Open as its own page

Skills for these tasks

Give your AI these skills and it does these tasks the expert way. Connect your AI once and it picks them up by itself.