AI Prompts for Writing Clean Code
Most AI prompts for clean code produce cosmetic fixes, not structural ones. This case study shows the exact prompt framework that helped one engineer cut her PR review rounds in half.
Clean this Python function for me.
def process(d, f=True):
r = []
for i in d:
if f:
if i > 0:
r.append(i*2)
else:
r.append(i)
return rThe Problem Sarah Faced
Sarah is a mid-level software engineer at a fintech startup. Her team of five ships features fast — sometimes too fast. Code reviews were becoming a weekly headache. Her pull requests kept getting flagged for the same issues: functions that did too much, variable names like
temp2dataObjHere's the stat that surprised her: a 2023 study by McKinsey found developers spend 35% of their working time on technical debt — reading confusing code, untangling dependencies, fixing bugs that clean code would have prevented. That's roughly 14 hours a week. Gone.
She turned to AI prompts for clean code, hoping to shave a few hours off. What she got was a complete rethink of how she wrote first drafts.
The Wrong Approach
Her first instinct was the same as most developers: paste the code, ask "make this cleaner."
Clean this Python function for me.
def process(d, f=True):
r = []
for i in d:
if f:
if i > 0:
r.append(i*2)
else:
r.append(i)
return rThe AI dutifully reformatted it. Added a docstring. Renamed
rresultf⚠️ Common mistake: Asking for "cleaner" code without specifying what dimension of cleanliness you care about. Clean means different things — readability, single responsibility, testability, performance. If you don't say which, the AI optimizes for the most visible surface changes.
The Correct Prompt
Sarah rewrote her approach. Instead of "make this cleaner," she gave context, a target reader, and a specific principle to apply.
You are a senior Python developer doing a code review focused on the Single Responsibility Principle.
Here is a function I wrote. Your job:
1. Identify every responsibility this function currently handles
2. Propose a refactored version that separates those responsibilities into clearly named functions
3. Explain each change in one sentence
4. Flag any variable names that don't communicate intent
Code:
def process(d, f=True):
r = []
for i in d:
if f:
if i > 0:
r.append(i*2)
else:
r.append(i)
return r
Language: Python 3.11
Context: This runs inside a data pipeline processing financial transactions.What this does: It forces the AI into a reviewer role rather than an editor role — which produces structural improvements, not cosmetic ones. The financial context also shifts the vocabulary toward domain-appropriate naming.
The AI returned three separate functions:
filter_positive_values()double_values()⚡ Pro tip: Add "explain each change in one sentence" to any refactoring prompt. You'll learn faster and catch cases where the AI's explanation doesn't match what the code actually does — which happens more than you'd expect.
Results and What Changed
Sarah's PR approval rate went from two rounds of review to one. Reviewers stopped commenting on structure and started focusing on logic and edge cases — which is what code review is actually for.
More importantly, she started applying the same framing to her own thinking before writing code. The prompt forced her to ask: "What are the responsibilities here?" That question alone changed how she planned functions.
Three concrete improvements she saw in her first two weeks:
- Function length dropped from an average of 47 lines to 18 lines
- Variable names became descriptive enough that junior devs stopped asking clarifying questions in PRs
- One senior dev asked her if she'd taken a clean code course — she hadn't
How to Apply This to Your Situation
The "role + principle + explain changes" framework works across languages and teams. Here are three industry-specific variations:
For JavaScript/TypeScript front-end developers: Add "flag any places where component concerns bleed into data-fetching logic" to isolate presentational code from business logic.
For backend Java developers: Specify "apply the Open/Closed Principle" to get suggestions that extend behavior without modifying existing classes — critical when you're maintaining legacy systems.
For data scientists writing production Python: Ask for "functions a junior data engineer could test in isolation" — this naturally pushes toward smaller, purer functions without requiring the AI to know your team's style guide.
⚡ Pro tip: Include your language version and runtime context. "Python 3.11 inside an async FastAPI handler" will get you better suggestions than just "Python." The AI can catch async-specific anti-patterns when it knows they're relevant.
The same principle applies for defining clean code at the team level. If your team follows Google's style guide, say so. If you're on an older codebase that still runs Python 2.7 (yes, it exists), say that too.
Next Steps
One more dimension worth adding: clean code looks different at different stages of a codebase. A greenfield module can follow ideal patterns. A 5-year-old module that 12 developers have touched has accumulated decisions that were right at the time and constraints that can't be undone in one sprint. When prompting for the latter, add "identify what can be refactored safely without changing public interfaces" — it gets you incremental improvements instead of a full rewrite proposal you can't act on.
The case_study here isn't really about one prompt. It's about replacing vague requests with structured ones. "Make this cleaner" is a dead-end instruction. "Apply this principle, explain each change, flag these specific issues" is a conversation.
For teams looking to systematize this, consider building a shared prompt library. PromptABCD is a solid option for saving and reusing your best-performing prompts — especially useful when you've tuned a code-review prompt for your specific stack and don't want to reconstruct it from scratch next month.
Start with one principle at a time. The clean code principles most worth starting with depend on your team's current pain: if PRs are slow because reviewers can't understand functions, start with SRP and naming. If you're hitting bugs at integration points, focus on error handling consistency first. Pick the principle that maps to your most recent incident and apply it systematically across the next sprint's code. Pick the SRP prompt above, run it on three functions this week, and compare the before-and-after. The pattern will click fast. And once it clicks, you'll find yourself applying it without the prompt — which is the real sign that the practice has taken hold.
Tracking Progress Over Time
One underused technique: run the same clean-code prompt on the same file every four weeks. Compare the AI's feedback. If it's flagging the same issues, the team's patterns haven't changed. If the feedback shifts from structural problems to minor style notes, you're moving in the right direction.
This kind of lightweight qualitative tracking is often more useful than coverage metrics alone. Clean code is partially about measurable complexity scores, but it's also about the questions that stop getting asked in PR reviews — and that's harder to quantify without a before/after lens.
⚡ Pro tip: Ask the AI to give your file a "maintainability score" out of 10 with a one-paragraph justification. It's not a rigorous metric, but it's surprisingly consistent across runs and useful as a rough north-star. Run it before and after a refactoring sprint to see if the needle moved.
Applying Clean Code Principles Across the Team
One challenge teams run into: clean code means different things to different developers. The senior engineer might care deeply about immutability. The mid-level dev focuses on naming. The junior dev just wants it to run. Without alignment, "make this cleaner" means something different in every PR.
A structured prompt approach actually helps here — because it externalizes the criteria. When you run "apply the Single Responsibility Principle and explain each change," everyone on the team sees the same framework. You can rotate which principle you're applying each sprint — one sprint focused on SRP, the next on DRY, the next on error handling consistency — and build shared vocabulary over time.
For tech leads specifically: consider building a clean code prompt that references your team's internal style guide directly. You can paste the relevant sections into the prompt context. An AI that knows your team calls API boundary classes "adapters" and your business logic layer "use cases" gives much better feedback than one reasoning from generic patterns.
You are reviewing code against our team's architecture guidelines. Our conventions:
- Controller layer: handles HTTP only, no business logic
- Use case layer: all business rules, no infrastructure concerns
- Repository layer: data access only, return domain objects not ORM models
Review the following code for violations of these layer boundaries. For each violation, identify which layer the code belongs in and why.
Code: [paste]What this does: Grounds the AI review in your actual architecture instead of generic clean code principles — catching the violations that matter most for your codebase's long-term health.
⚡ Pro tip: Run this layering-check prompt as part of your architecture review process, not just individual code review. It catches cross-cutting concerns that accumulate silently over time and become expensive to untangle later.
Continue Reading
Save the prompts from this post
PromptABCD is a free prompt manager. Paste, organize, and reuse your best AI prompts — no more hunting through chat history.
