AIO APEX
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

O Consultor de Refatoração de Código: Correções Antes e Depois com uma Pontuação de Risco para Cada Uma

Compartilhar:
O Consultor de Refatoração de Código: Correções Antes e Depois com uma Pontuação de Risco para Cada Uma

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.

A maioria dos prompts de refatoração produz uma reescrita gigante da sua função e espera que esteja correta. Isso é ao contrário para código de produção real — uma reescrita única e abrangente é exatamente o tipo de mudança mais difícil de revisar, mais difícil de testar e com maior probabilidade de esconder uma regressão dentro de um diff grande demais para que alguém possa verificar adequadamente. Este prompt faz o oposto: ele divide a limpeza em pedaços independentes e individualmente mescláveis, e os classifica de acordo com o quanto podem quebrar.

Por que a pontuação de risco vem antes da pontuação de qualidade do código

Uma refatoração que melhora a legibilidade mas não altera nenhum comportamento observável é fundamentalmente diferente de uma que toca a lógica real, mesmo que ambas pareçam diffs de tamanho semelhante. O prompt força essa distinção ao pedir uma Pontuação de Risco baseada em três fatores específicos: quanto comportamento a mudança afeta, se os testes existentes detectariam uma regressão, e se a mudança é puramente estrutural ou altera a lógica. Isso transforma uma vaga sensação de "isto parece arriscado" em uma decisão repetível que o modelo precisa justificar.

Por que correções de baixo risco vêm primeiro

Ordenar as sugestões do menor para o maior risco não é apenas uma questão de segurança — é uma questão de impulso. Equipes que evitam uma função ruim geralmente a evitam por completo, incluindo as partes que são trivialmente seguras de corrigir. Conseguir algumas vitórias de baixo risco primeiro (variáveis renomeadas, validação desduplicada, substituição de booleanos por parâmetros nomeados) constrói confiança e reduz o arquivo antes que alguém tenha que tomar uma decisão mais difícil sobre as mudanças estruturais mais arriscadas.

Por que ele pede cobertura de testes antes de sugerir as coisas arriscadas

A forma mais comum de a refatoração dar errado é pular direto para a parte satisfatória — dividir uma função inchada em pedaços limpos e bem nomeados — sem verificar se os testes atuais realmente exercitam os caminhos de código que estão sendo alterados. Este prompt verifica explicitamente sua cobertura de testes declarada e, se ela for fraca, informa qual teste escrever antes de tentar as refatorações de maior risco, em vez de depois que algo quebrar em produção.

Por que a divisão da função é sinalizada como seu próprio PR

Dividir uma função com múltiplas responsabilidades em funções separadas geralmente é a "verdadeira" correção que todos querem, mas também é a mudança com maior probabilidade de alterar comportamentos sutis — caminhos de tratamento de erros, estados de execução parcial, ordenação de efeitos colaterais. O prompt trata deliberadamente isso como uma refatoração separada de maior risco, a ser feita somente após as limpezas mais seguras terem sido mescladas e estiverem estáveis, em vez de agrupá-la na mesma alteração que as vitórias fáceis.

Como adaptá-lo

Seja específico sobre suas restrições — uma função chamada de 40 lugares se comporta de maneira muito diferente sob pressão de refatoração do que uma chamada de um único arquivo de teste. Se você realmente não tem cobertura de testes, espere que o modelo recomende escrever testes antes de mexer em qualquer coisa além do primeiro ou segundo item de baixo risco, e trate essa recomendação como a resposta real, não como uma formalidade a ser ignorada.

prompt-engineeringcode reviewdeveloper-productivitycode-refactoringtechnical-debt
Compartilhar: