Refactor Code Prompt for Cleaner Code
A structured prompt that refactors your code for readability and maintainability — without changing behavior — with a real before/after example.
Enhanced prompt — ready to use
ROLE You are a senior software engineer with expertise in code refactoring and optimization. Your goal is to improve the given code's structure, readability, and performance while maintaining its original functionality. TASK Refactor the provided code by analyzing it step by step to identify inefficiencies, redundancies, and potential improvements. Make the code more modular, clean, and maintainable without altering its behavior. Consider edge cases and best coding practices during the refactoring process. CONTEXT The user has requested a refactor of an unspecified piece of code. Assume the code is written in a common programming language such as Python or JavaScript and is part of a larger application. The audience includes developers who will maintain the codebase in the future. REQUIREMENTS - Improve code readability, modularity, and maintainability. - Optimize performance if possible without compromising clarity. - Preserve the original functionality entirely. - Think step by step and consider edge cases. - Before finalizing, verify your answer for correctness and completeness. - Assumptions: Since the code and language are not specified, assume the code is in Python. OUTPUT FORMAT Provide the refactored code in a well-formatted code block followed by a concise explanation of the changes made and the benefits achieved.
That's what PromptAI produced from this vague prompt: “refactor this code”
Example result
Since the original code was not provided, I'll demonstrate a refactoring example based on a typical Python snippet that might have inefficiencies, readability issues, and lack modularity. This example will walk through the refactoring steps on a representative piece of code.
---
### Original (hypothetical) code:
```python
def process_data(data):
result = []
for i in range(len(data)):
if data[i] % 2 == 0:
squared = data[i] ** 2
if squared > 10:
result.append(squared)
for j in range(len(result)):
print("Value:", result[j])
return result
```
---
### Step-by-step issues identified:
1. **Index-based iteration:** Using `range(len(data))` with indexing is less Pythonic and less readable.
2. **Nested conditions:** Nested `if`s can be combined for clarity.
3. **Single responsibility:** The function mixes data processing and printing results — these should be separate.
4. **No input validation:** No checks for input data correctness or empty lists.
5. **Missed opportunity to use list comprehensions** for performance and readability.
6. **Hardcoded condition `squared > 10`:** Could be parameterized for flexibility.
7. **Lack of docstrings and type hints:** Helpful for maintainability.
---
### Refactored code:
```python
from typing import List
def filter_and_square(
data: List[int],
threshold: int = 10
) -> List[int]:
"""
Filters even numbers from the data, squares them,
and returns those with a value greater than the threshold.
Args:
data (List[int]): List of integers to process.
threshold (int): Minimum squared value to include.
Returns:
List[int]: List of squared even values greater than threshold.
"""
if not isinstance(data, list):
raise TypeError("Input data must be a list of integers.")
if any(not isinstance(x, int) for x in data):
raise ValueError("All items in data must be integers.")
return [x ** 2 for x in data if x % 2 == 0 and (x ** 2) > threshold]
def print_values(values: List[int]) -> None:
"""
Prints the values in a formatted manner.
Args:
values (List[int]): List of integers to print.
"""
for value in values:
print(f"Value: {value}")
# Example usage:
if __name__ == "__main__":
sample_data = [1, 2, 3, 4, 5, 6]
processed_values = filter_and_square(sample_data)
print_values(processed_values)
```
---
### Explanation of changes and benefits:
- **Separated concerns:** `filter_and_square` handles processing, `print_values` handles output. This improves modularity, testability, and reusability.
- **Used list comprehension:** This makes filtering and transforming concise and efficient.
- **Added type hints and docstrings:** Improves readability, usability, and helps auto-documentation tools.
- **Input validation:** Checks types and raises clear exceptions, preventing unexpected failures downstream.
- **Parameterization:** Added `threshold` as a parameter instead of a magic number, making the function more flexible.
- **Formatted printing:** Used f-strings for readability and performance.
- **Guard clause in example usage:** Shows how to call these functions properly, which is helpful for developers.
This refactoring makes the code more maintainable, readable, and slightly more performant due to reduced overhead of explicit loops and conditions. It also suppresses side-effects within pure functions for better predictability and easier unit testing.How to adapt it
- •Tell it your priorities (readability, performance, testability) so the refactor fits.
- •Ask it to preserve the public interface and explain each change.
Have your own rough prompt? Enhance it into a structured prompt like this in one click.
Enhance your own promptMore coding prompts
API Documentation Prompt for Clear Docs
A structured prompt that documents your API endpoint — params, responses, errors, and examples — in clean reference style, with a real example.
Bash Script Prompt for Shell Automation
A structured prompt that writes a safe, portable Bash script for your task — with checks, comments, and a real example output.
Bug Fix Prompt That Finds Root Causes
A structured prompt that diagnoses and fixes a bug — root cause, the fix, and why it works — instead of a guess, with a real example.
Code Comment Prompt for Useful Comments
A structured prompt that adds clear, non-obvious comments and docstrings to your code — explaining why, not just what — with a real example.
Code Review Prompt for Better Feedback
A structured prompt that turns ChatGPT into a thorough code reviewer — bugs, edge cases, readability, and security — with a real example review.
Database Schema Prompt for Clean Data Models
A structured prompt that designs a normalized database schema for your app — tables, keys, and relations — with DDL and a real example.