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

El Asesor de Refactorización de Código: Arreglos Antes y Después con una Puntuación de Riesgo para Cada Uno

Compartir:
El Asesor de Refactorización de Código: Arreglos Antes y Después con una Puntuación de Riesgo para Cada Uno

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.

La mayoría de los prompts de refactorización producen una reescritura gigante de tu función y esperan que sea correcta. Eso está al revés para código de producción real: una reescritura única y masiva es exactamente el tipo de cambio más difícil de revisar, más difícil de probar y con más probabilidades de ocultar una regresión dentro de un diff demasiado grande para que nadie lo verifique correctamente. Este prompt hace lo contrario: divide la limpieza en piezas independientes y fusionables individualmente, y las clasifica según cuánto podrían romper.

Por qué la puntuación de riesgo va antes que la puntuación de calidad del código

Una refactorización que mejora la legibilidad pero no cambia ningún comportamiento observable es fundamentalmente diferente de una que toca la lógica real, incluso si ambas parecen diffs de tamaño similar. El prompt fuerza esta distinción pidiendo una Puntuación de Riesgo basada en tres factores específicos: cuánto comportamiento toca el cambio, si las pruebas existentes detectarían una regresión, y si el cambio es puramente estructural o altera la lógica. Esto convierte una vaga sensación de "esto se siente riesgoso" en una decisión repetible que el modelo debe justificar.

Por qué los arreglos de bajo riesgo vienen primero

Ordenar las sugerencias de menor a mayor riesgo no es solo cuestión de seguridad, sino de impulso. Los equipos que evitan una función mala a menudo la evitan por completo, incluyendo las partes que son trivialmente seguras de arreglar. Conseguir algunas victorias de bajo riesgo primero (variables renombradas, validación desduplicada, banderas booleanas reemplazadas por parámetros nombrados) genera confianza y reduce el archivo antes de que alguien tenga que tomar una decisión más difícil sobre los cambios estructurales más riesgosos.

Por qué pide cobertura de pruebas antes de sugerir lo riesgoso

La forma más común en que la refactorización sale mal es saltar directamente a la parte satisfactoria — dividir una función hinchada en piezas limpias y bien nombradas — sin verificar que las pruebas actuales realmente ejerciten las rutas de código que se están modificando. Este prompt verifica explícitamente tu cobertura de pruebas declarada y, si es débil, te dice qué prueba escribir antes de intentar las refactorizaciones de mayor riesgo, en lugar de después de que algo se rompa en producción.

Por qué la división de la función se marca como su propio PR

Dividir una función con múltiples responsabilidades en funciones separadas suele ser el "verdadero" arreglo que todos quieren, pero también es el cambio con más probabilidades de alterar comportamientos sutiles — rutas de manejo de errores, estados de ejecución parcial, orden de efectos secundarios. El prompt trata deliberadamente esto como una refactorización separada de mayor riesgo que debe realizarse solo después de que las limpiezas más seguras estén fusionadas y estables, en lugar de agruparlo en el mismo cambio que las victorias fáciles.

Cómo adaptarlo

Sé específico sobre tus restricciones: una función llamada desde 40 lugares se comporta de manera muy diferente bajo presión de refactorización que una llamada desde un solo archivo de prueba. Si realmente no tienes cobertura de pruebas, espera que el modelo recomiende escribir pruebas antes de tocar cualquier cosa más allá de los primeros uno o dos elementos de bajo riesgo, y trata esa recomendación como la respuesta real, no como una formalidad que debas saltar.

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