Works best with Claude Opus 4.8 or Sonnet 5 for large functions (context window and code reasoning matter more than raw speed here); GPT-5.4 is a solid alternative. Avoid smaller/faster models for this — risk scoring requires holding the whole function's logic in view at once.You've inherited a 400-line function that everyone on the team avoids touching because it 'works, mostly' and nobody remembers why it's structured the way it is. You need to clean it up before adding a new feature, but you don't have time to rewrite it from scratch and can't afford to break the parts that work.Developer Tools

مشاور بازسازی کد: اصلاحات قبل و بعد به همراه امتیاز ریسک برای هر مورد

اشتراک‌گذاری:
مشاور بازسازی کد: اصلاحات قبل و بعد به همراه امتیاز ریسک برای هر مورد

Why this prompt matters

Developers now spend 23-42% of their work week dealing with technical debt and bad code — the Stripe Developer Coefficient study puts the global cost at $85 billion in lost productivity a year. The failure mode isn't not knowing code is bad; it's not knowing which fix is safe to make first. A one-standard-deviation rise in an organization's debt-to-code ratio corresponds to a 31% jump in defect density — refactoring the wrong part first, or all of it at once, is how technical debt cleanup itself introduces new bugs.

What we use it for

You've inherited a 400-line function that everyone on the team avoids touching because it 'works, mostly' and nobody remembers why it's structured the way it is. You need to clean it up before adding a new feature, but you don't have time to rewrite it from scratch and can't afford to break the parts that work.

Prompt

You are a senior software engineer with expertise in refactoring legacy code without introducing regressions. You are conservative by default — you flag risk honestly rather than being falsely reassuring.

CONTEXT:
Language/framework: [YOUR LANGUAGE, e.g. "TypeScript, Node.js, Express"]
What this code does: [ONE-SENTENCE DESCRIPTION OF THE FUNCTION'S PURPOSE]
Known problems (if any): [WHAT YOU ALREADY SUSPECT IS WRONG, e.g. "deeply nested conditionals, unclear variable names, does three unrelated things"]
Test coverage: [DESCRIBE CURRENT TESTS, e.g. "one integration test covering the happy path only" or "none"]
Constraints: [ANYTHING THAT CANNOT CHANGE, e.g. "the public function signature must stay identical, this is called from 40+ places"]

TASK:
Review the code below and identify 3-6 specific, independent refactoring opportunities. For EACH one:
1. Name the problem (e.g. "duplicated validation logic", "mixed abstraction levels", "unclear boolean flag parameter").
2. Show the BEFORE code snippet (just the relevant lines, not the whole function).
3. Show the AFTER code snippet with the fix applied.
4. Assign a Risk Score (Low/Medium/High) based on: how much of the function's behavior the change touches, whether existing tests would catch a regression, and whether the change is purely structural (safe) or alters logic/behavior (riskier).
5. State what you'd want to verify manually or via a new test before merging this specific change.

CONSTRAINTS:
- Do NOT rewrite the entire function in one pass. Each refactor must be independently applicable — I need to be able to accept refactor #2 without necessarily taking #4.
- Order your suggestions from LOWEST risk to HIGHEST risk, so I can bank easy wins first.
- If the function is doing more than one job, say so explicitly and suggest a split — but still give me the low-risk internal cleanups first, since a full split is inherently higher-risk.
- Do not suggest changes that alter the function's observable behavior unless you flag it as Medium or High risk with a clear explanation of what changes.
- If test coverage is described as weak or absent, recommend which specific test(s) to write BEFORE attempting the Medium/High risk refactors, not after.

OUTPUT FORMAT:
## Refactor 1: [Problem name] — Risk: [Low/Medium/High]
**Before:**
```
[code]
```
**After:**
```
[code]
```
**Verify before merging:** [what to check or test]

[repeat for each refactor, low to high risk]

## Summary
[One paragraph: overall assessment of the function's health, and the recommended order of operations]

CODE TO REVIEW:
[PASTE YOUR FUNCTION OR CODE BLOCK HERE]

Result

Refactor 1: Duplicated validation logic — Risk: Low

Before:

if (!user.email || user.email.length === 0) { throw new Error('Email required'); }
if (!user.name || user.name.length === 0) { throw new Error('Name required'); }
if (!user.phone || user.phone.length === 0) { throw new Error('Phone required'); }

After:

const requiredFields = ['email', 'name', 'phone'];
for (const field of requiredFields) {
  if (!user[field]?.length) throw new Error(`${field} required`);
}

Verify before merging: Confirm error message format isn't parsed elsewhere by exact string match — the field name capitalization changed slightly.

Refactor 2: Unclear boolean flag parameter — Risk: Low

Before:

function processOrder(order, flag) {
  if (flag) { applyDiscount(order); }
  ...
}

After:

function processOrder(order, { applyLoyaltyDiscount }) {
  if (applyLoyaltyDiscount) { applyDiscount(order); }
  ...
}

Verify before merging: Update all 6 call sites to pass a named object instead of a positional boolean — purely mechanical, no behavior change, but touches every caller.

Refactor 3: Deeply nested conditionals — Risk: Medium

Before:

if (user.active) {
  if (user.subscription) {
    if (user.subscription.tier === 'pro') {
      // 15 more lines
    }
  }
}

After:

if (!user.active) return;
if (!user.subscription) return;
if (user.subscription.tier !== 'pro') return;
// 15 more lines, now unindented

Verify before merging: Early returns change control flow if there's an else branch further down handling the negative case elsewhere in the original function — check for one before applying. Write a test for the non-pro-tier path specifically, since current coverage doesn't exercise it.

Refactor 4: Function does three unrelated things — Risk: High

Before: Single 400-line function handles validation, discount calculation, and email notification in sequence.

After: Split into validateOrder(), calculateDiscount(), and notifyCustomer(), called in sequence from a thin orchestrator function.

Verify before merging: This changes the function's shape enough that any code relying on partial execution (e.g. catching an error mid-function and still sending a notification) will behave differently. Do NOT attempt this split until Refactors 1-3 are merged and you have integration test coverage for all three code paths — this should be its own PR, reviewed separately.

Summary

This function is moderately unhealthy but not unsalvageable. Refactors 1-2 are safe, mechanical wins you can ship today. Refactor 3 needs one new test first but is still low-stakes. Refactor 4 (the actual split) is the real fix but should wait until the others are merged and stable — attempting all four at once is how a cleanup PR turns into a production incident.

اکثر prompt‌های refactoring یک بازنویسی کامل و یکجا از function شما تولید می‌کنند و امیدوارند که نتیجه صحیح باشد. این رویکرد برای کد واقعی production کاملاً معکوس است — یک بازنویسی گسترده و یکجا دقیقاً همان نوع تغییری است که بررسی آن دشوارترین، آزمایش آن سخت‌ترین، و احتمال پنهان‌شدن یک regression در یک diff بیش از حد بزرگ در آن بالاترین است. این prompt عکس آن عمل می‌کند: پاک‌سازی را به بخش‌های مستقل و قابل merge به‌صورت جداگانه تقسیم می‌کند و آن‌ها را بر اساس میزان خطر شکست احتمالی رتبه‌بندی می‌نماید.

چرا امتیازدهی به ریسک پیش از امتیازدهی به کیفیت کد انجام می‌شود

یک refactor که خوانایی را بهبود می‌بخشد اما هیچ رفتار قابل مشاهده‌ای را تغییر نمی‌دهد، ذاتاً با refactorی که منطق واقعی را دستکاری می‌کند متفاوت است، حتی اگر هر دو به نظر diff‌هایی با اندازه مشابه باشند. این prompt با درخواست یک Risk Score بر اساس سه عامل مشخص، این تمایز را اجباری می‌کند: میزان تأثیر تغییر بر رفتار، اینکه آیا تست‌های موجود یک regression را شناسایی می‌کنند یا نه، و اینکه آیا تغییر صرفاً ساختاری است یا منطق را دگرگون می‌سازد. این امر حس مبهم «این ریسک‌دار به نظر می‌رسد» را به یک قضاوت تکرارپذیر تبدیل می‌کند که مدل باید آن را توجیه کند.

چرا اصلاحات کم‌ریسک در اولویت قرار دارند

مرتب‌سازی پیشنهادها از کمترین تا بیشترین ریسک تنها به خاطر ایمنی نیست — بلکه به خاطر حفظ انگیزه و شتاب کار است. تیم‌هایی که از یک function بد اجتناب می‌کنند، اغلب آن را به‌طور کامل نادیده می‌گیرند، از جمله بخش‌هایی که اصلاح آن‌ها کاملاً بی‌خطر است. ثبت چند پیروزی کم‌ریسک در ابتدا (تغییر نام متغیرها، حذف تکراری‌های validation، جایگزینی boolean flag‌ها با پارامترهای نام‌گذاری‌شده) اعتماد ایجاد می‌کند و حجم فایل را کاهش می‌دهد، پیش از آنکه کسی مجبور شود تصمیم سخت‌تری درباره تغییرات ساختاری پرریسک‌تر اتخاذ کند.

چرا پیش از پیشنهاد موارد پرریسک، پوشش تست بررسی می‌شود

رایج‌ترین دلیل شکست refactoring این است که مستقیم به سراغ بخش جذاب می‌روند — تقسیم یک function حجیم به بخش‌های تمیز و خوش‌نام — بدون آنکه تأیید کنند تست‌های موجود واقعاً مسیرهای کدی را که تغییر می‌یابند پوشش می‌دهند. این prompt به‌صراحت پوشش تست اعلام‌شده را بررسی می‌کند و در صورت ناکافی بودن آن، مشخص می‌سازد که کدام تست باید پیش از اقدام به refactorهای پرریسک‌تر نوشته شود، نه پس از آنکه چیزی در production خراب گردد.

چرا تقسیم function به‌عنوان یک PR مستقل علامت‌گذاری می‌شود

تقسیم یک function چندمسئولیتی به function‌های جداگانه معمولاً «اصلاح واقعی» مورد نظر همه است، اما همین تغییر بیشترین احتمال را دارد که رفتارهای ظریف را دگرگون کند — مسیرهای مدیریت خطا، حالت‌های اجرای ناقص، ترتیب side-effect‌ها. این prompt عمداً آن را به‌عنوان یک refactor جداگانه و پرریسک‌تر در نظر می‌گیرد که تنها پس از merge و پایدار شدن پاک‌سازی‌های ایمن‌تر انجام می‌شود، نه اینکه در یک تغییر واحد با دستاوردهای آسان ترکیب گردد.

چگونه آن را تطبیق دهید

درباره محدودیت‌های خود دقیق باشید — یک function که از ۴۰ جا فراخوانی می‌شود، زیر فشار refactoring رفتار بسیار متفاوتی نسبت به function‌ای دارد که از یک فایل تست واحد فراخوانی می‌شود. اگر واقعاً هیچ پوشش تستی ندارید، انتظار داشته باشید که مدل پیش از دست زدن به هر چیزی فراتر از یک یا دو مورد اول کم‌ریسک، نوشتن تست را توصیه کند؛ و آن توصیه را پاسخ واقعی تلقی کنید، نه تشریفاتی که باید از آن گذشت.

prompt-engineeringcode reviewdeveloper-productivitycode-refactoringtechnical-debt
اشتراک‌گذاری: