35 Prompts for Code Review & Refactoring

The checkout view is 340 lines. It validates the cart, applies a promo code, calculates tax for three jurisdictions, creates a payment intent, writes an order row, decrements stock, and sends a confirmation email. It works in staging. It has never been loaded in a way that matters, and last Friday it charged a customer twice because the payment webhook fired while the user pressed the button again. Nobody wants to touch it, which is exactly why it stays 340 lines long.

Refactoring that kind of module is not one task. It is a sequence of small, verifiable reviews, each with a narrow question. The thirty-five prompts below are organized that way: orient yourself in unfamiliar code, hunt the failures that cost money or leak data, rewrite one function at a time, and finish with tests and a pull request a reviewer can actually approve. For the broader review vocabulary, see the coding prompt examples comparison.

How to Use This List

Paste the prompt, then paste the actual code. Every prompt here assumes real source rather than a paraphrase, because review quality collapses the moment the code is summarized. Keep each prompt scoped to one function or file; a full-module review in one pass produces shallow comments. If something is genuinely broken rather than merely ugly, switch to the debugging workflow instead of a review prompt.

First-Pass Review and Triage

1. Orient in unfamiliar code. The first thing to run on a module you inherited.

Here is a module I did not write: [CODE]. Explain what it does in plain language, list the responsibilities it carries, and rank them by how much risk each adds to the checkout flow.

2. Rank the problems. A review with 30 comments is a review nobody acts on.

Review this code: [CODE]. List every issue you find, then rank them from 1 to 10 by severity and give me only the top five to fix this week, with a one-line reason for each ranking.

3. Locate the risky lines. Point the review at the parts that can actually hurt.

In this file: [CODE], identify the lines most likely to cause a production incident. Focus on state changes, external calls, and anything that writes to the database. Quote the lines and explain the failure mode for each.

4. Explain one function precisely. Write down the contract before you change anything.

Explain this function in detail: [FUNCTION]. Cover its inputs, outputs, side effects, assumptions about the database state, and the two conditions under which it silently returns an incorrect result.

5. Find the dead code. Deletions are the cheapest refactor available.

Here is the checkout module: [CODE]. Identify code that is never reached, branches the current callers cannot take, and functions no longer used. For each, tell me what breaks if I delete it.

6. Review the naming. Naming problems hide logic problems.

Review the names in this code: [CODE]. Flag names that hide a side effect, names that suggest the wrong type, and booleans that are hard to read in a condition. Suggest replacements and explain what each rename clarifies.

7. Review the comments and docstrings. Stale comments are worse than none.

Here is my commented code: [CODE]. For every comment, tell me whether it is still accurate, whether it explains why rather than what, and which ones should be deleted because the code already says it.

8. Find duplicated logic. Checkout modules accumulate three versions of the same tax rule.

These functions contain overlapping logic: [CODE]. Identify the duplicated rules, name the single source of truth each duplicate should defer to, and show me the extracted helper without changing behavior.

9. Flag missing error handling. Where happy-path code meets the payment provider.

Audit the error handling in this code: [CODE]. List every place an exception could escape, every external call without a timeout, and every bare except clause. Rank the gaps by likelihood of occurring in production.

Money, Security, and Data Integrity

10. Money precision audit. Floats in a checkout are a bug waiting for a customer.

Audit every monetary calculation in this code: [CODE]. Flag any use of float, any place where rounding happens silently, and any conversion between currencies or units without an explicit rate. Show the corrected lines using Decimal.

11. Rounding direction. Whose cent is it, and who decides.

For each rounding point in this code: [CODE], tell me which direction it rounds, who benefits, and whether the choice is documented. Include the total drift if 10,000 orders used this rule.

12. Idempotency check. The core defense against the double charge.

Review this order creation flow for idempotency: [CODE]. Identify every path where a retry or a double click could create a second order or a second charge, and show the minimal change that makes the operation safe to repeat.

13. Race condition hunt. Two requests, one stock counter.

Look for race conditions in this code: [CODE]. Focus on concurrent writes to inventory, cart totals, and coupon usage. For each race, describe the interleaving that triggers it and whether a transaction, a lock, or a unique constraint is the right fix.

14. Permission check on the view. Marketing pages can be public; order pages cannot.

Review the access control in this Django view: [CODE]. Tell me whether every code path verifies that the requesting user owns the order, and show the specific request that would let one customer read another customer's data.

15. Sensitive data audit. What ends up in logs and error reports.

Audit this code for sensitive data exposure: [CODE]. Flag anywhere a card number, token, email, or address could reach a log, an exception message, or a third-party error tracker. Show the redacted version of each line.

16. Oversell prevention. The failure that shows up as an angry support ticket.

Review this inventory decrement logic: [CODE]. Explain what happens when two orders for the last unit are placed within the same second, and rewrite the section so the second order fails cleanly with a user-facing message.

17. Audit trail review. Six months later, someone will ask who changed the price.

Review what this checkout flow records for later auditing: [CODE]. List the events a finance or support team would need to reconstruct an order, identify which ones are missing, and suggest where to emit them.

Refactoring One Function at a Time

18. Extract a function. The single highest-value move in a long view.

This function is too long: [FUNCTION]. Identify the natural seams, propose two or three extracted functions with clear names and single responsibilities, and show the refactored version with identical behavior.

19. Reduce nesting. Guard clauses read better than pyramids.

Rewrite this function to reduce nesting: [FUNCTION]. Use early returns and guard clauses, keep the same behavior, and tell me which branch was hardest to follow before the change and why.

20. Replace a conditional ladder. Tax rules belong in data, not in seven elif branches.

This function is a chain of conditionals: [FUNCTION]. Propose a table-driven or strategy-based replacement using these rules: [RULES]. Show the new structure and name the test cases that must still pass.

21. Introduce a service layer. Move business rules out of the view.

Here is my Django view: [CODE]. Extract the business logic into a service function, keep the view responsible only for parsing the request and shaping the response, and show both files after the change.

22. Separate orchestration from computation. One function decides, the other calculates.

This code mixes decision-making with calculation: [CODE]. Split it into a pure calculation function with no side effects and an orchestration function that performs the I/O, then show which one becomes trivially testable.

23. Inject the external client. Hard-coded providers make tests slow and brittle.

My payment client is instantiated inside the function: [CODE]. Refactor it so the client is passed in, show how the production caller changes, and show the fake client a test would use instead.

24. Tighten database access. Fewer round trips, same behavior.

Review the database access pattern here: [CODE]. Identify reads that could be combined, writes that could be deferred, and any loop that issues a query per iteration. Show the refactored version and estimate the query count before and after.

25. Add type hints. Cheap documentation that a checker enforces.

Add type hints to this code: [CODE]. Use types that reflect reality rather than the easiest annotation, flag any place where the correct type reveals a bug, and note where Optional is genuinely required.

26. Behavior-preserving refactor. The rule that keeps a refactor reviewable.

Refactor this function without changing observable behavior: [FUNCTION]. State explicitly what counts as observable behavior here, list any place where you were tempted to also change logic, and keep that list separate from the refactor.

Tests, Performance, and the Pull Request

27. Test plan for the module. Vocabulary first, then cases.

Here is the checkout module: [CODE]. Write a test plan covering happy path, empty cart, expired coupon, payment failure, and webhook retry. For each case, state the setup, the action, and the single assertion that proves the behavior.

28. Regression test for a bug. The bug that charged twice deserves a permanent guard.

This bug occurred in production: [BUG DESCRIPTION]. From this code: [CODE], write a regression test that fails on the current version and passes after the fix. Include the exact fixture data needed.

29. Edge case list. Everything the happy path forgot.

List the edge cases this function will encounter in real usage: [FUNCTION]. Include zero quantities, decimal quantities, maximum order size, concurrent modification, and timezone-sensitive dates. Rank by likelihood and mark which ones lack a test.

30. Find the N+1 query. The performance bug that only appears at scale.

Review this ORM code for N+1 queries: [CODE]. Identify each loop that triggers a query, show the select_related or prefetch_related fix, and tell me how many queries the page runs before and after for a cart with 12 items.

31. Index recommendation. Justify it with the query, not a hunch.

These queries run on every checkout: [QUERIES]. Recommend indexes, explain the access pattern each one supports, and warn me about any index that would slow down writes to the orders table without enough read benefit.

32. Write the PR description. Reviewers approve faster when the why comes first.

Write a pull request description for this change: [DIFF OR SUMMARY]. Structure it as problem, change, what I deliberately did not touch, and how to verify. Keep it under 250 words and skip the checklist boilerplate.

33. Write review comments for a junior. Tone is part of the deliverable.

Here is a diff from a junior developer: [DIFF]. Write review comments that are specific, explain the reasoning behind each request, and separate blocking issues from optional suggestions. Do not soften a real bug into a suggestion.

34. Self-review checklist. Run this before you open the pull request.

Build a self-review checklist for changes to a payment-adjacent module. Include checks for money precision, idempotency, migrations, feature flags, sensitive-data logging, and rollback. Keep it to 12 items verifiable in under 15 minutes.

35. Split the work into reviewable PRs. One giant refactor never gets merged cleanly.

I need to refactor this module: [CODE]. Break the work into three sequential pull requests where each one is independently shippable and keeps tests green. For each PR, give the scope, the risk, and the rollback trigger.

Bonus Techniques

Three habits that improve the whole process. First, always ask for a severity ranking rather than a list, because an unpriced list of 40 findings gives you no way to decide what to do Monday. Second, keep a short file of the prompts that caught real bugs in your module and re-run them after every significant change, turning one-time review into a repeating check. Third, when the refactor touches several layers at once, step up a level and ask the architecture-level prompt framing whether the boundary itself is wrong. If it is, the local cleanup will not survive the next feature.

Sources & Notes

These prompts were written against a Django e-commerce checkout module that had grown into a 340-line view handling cart validation, tax, discounts, payment, and inventory. The sequencing follows the order that works: understand the module, find what costs money, change one function at a time, then lock behavior with tests.

Two cautions. Models are unreliable at counting queries or predicting real index performance, so treat prompts 30 and 31 as starting points and confirm with your database. And never paste live credentials, customer records, or payment tokens into a review prompt; replace them with placeholders first.

声明:1.本站所有文章,如无特殊说明或标注,均为本站原创发布。本网站中【文本生成/文生图】使用了DeeSseek人工智能生成内容技术, 算法来源说明:本网站未自行开发、训练或部署深度合成算法,所使用的人工智能算法来自:DeepSeek、Chatgpt、Google Gemini。 2.为了网站加载速度优化,本站预览图片进行压缩处理,所以有些不是太清晰,并不影响AI提示词生图、AI设计等内容。3.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。--GUUNN.COM