Refactor Code
Purpose
Improve the internal structure of code without changing its observable behavior, so that the next change becomes cheap and safe, and do it in steps small enough to verify and review.
When to use
- A feature or fix is blocked by code that is hard to understand or change ("make the change easy, then make the easy change").
- Review or analysis found smells worth fixing in actively changing code.
- Duplicated logic must be consolidated before it diverges further.
When not to use
- Only an assessment of problems is needed, no changes. Use
clean-code-review or tech-debt-assessment.
- The code is not yet understood. Use
legacy-code-comprehension first.
- The goal is speed, not structure. Use
performance-optimization.
Inputs
Required:
- The code to refactor and the reason (the upcoming change or the pain it causes).
Optional, improves quality:
- Existing tests, coding standards, language/framework version, constraints (public API must not change, no new dependencies).
If there are no tests and none can be run, say so and start with characterization tests; never claim behavior is preserved without evidence.
Process
- State the goal in terms of the next change ("adding a discount type should touch one class").
- Identify the smells that block that goal (long function, duplicated conditional, feature envy, primitive obsession, shotgun surgery); ignore cosmetic ones.
- Check the safety net: which behaviors are covered by tests? Add characterization tests for uncovered paths, including odd current behavior (record it, do not fix it now).
- Choose named refactorings from the catalog vocabulary and order them from low risk (rename, extract variable, extract function) to structural (move function, replace conditional with polymorphism, split phase).
- Apply one refactoring per step; after each step the code compiles and tests pass. Keep behavior changes and bug fixes out of refactoring commits.
- Keep public contracts stable unless agreed; when a signature must change, use a parallel change (add new, migrate callers, remove old).
- Watch for semantic traps: evaluation order, side effects in moved code, null/empty handling, exception types, floating-point or rounding differences, thread safety of extracted state.
- After the sequence, compare before/after against the goal and remove scaffolding.
- Report each step with its refactoring name, suggested commit boundary and any behavior quirk discovered.
- If the goal continues, suggest
unit-test-writing where characterization tests were missing or code-review to review the refactored change.
Output format
# Refactoring: <unit>
Goal: <what the next change should look like>
Safety net: <existing tests / added characterization tests>
## Smells Addressed
| Smell | Location | Why it blocks the goal |
## Steps
| # | Refactoring | Change | Tests green? |
|---|---|---|---|
| 1 | Extract Function | `applySeasonalDiscount` from lines .. | Yes |
## Result
<final code or diff>
## Discovered Behavior Quirks (not changed)
- ...
Quality checklist
Common pitfalls
- "Big bang" rewrite labeled as refactoring. If it cannot be done in green steps, it is a rewrite and needs its own plan.
- Refactoring code nobody will change again. Prioritize by change frequency and upcoming work.
- Silently "fixing" odd behavior during extraction; callers may depend on it. Record it and fix in a separate change.
Example
Input: "calculatePrice has nested if/else for customer type and discount type; adding a new discount breaks things."
Excerpt of output:
- Characterization tests: 12 combinations of customer type × discount type, including the current rounding of half cents (quirk recorded).
- Split Phase: separate "determine applicable discounts" from "apply discounts to price".
- Replace Conditional with Polymorphism:
Discount interface with one implementation per type; new type = new class + registration.
1---2name: refactoring3description: "Refactors code safely by identifying the smells that matter for the next change, securing behavior with characterization tests, and applying named refactorings (Extract Function, Replace Conditional with Polymorphism, Introduce Parameter Object, etc.) in small behavior-preserving steps. Use when code is hard to change, before adding a feature to messy code, or when someone asks to clean up, restructure or refactor code without changing behavior."4license: MIT5metadata:6 source: https://skillmd.com/skills/muratdincer/refactoring7 version: "1.0.0"8 language: en9 category: 05-engineering10 role: developer11 area: coding12 title: "Refactor code"13 related: "clean-code-review, legacy-code-comprehension, unit-test-writing, tech-debt-assessment, code-review"14 prompt: "Refactor this 200-line calculatePrice method; I need to add a new discount type next sprint and every change here breaks something."15---1617# Refactor Code1819## Purpose20Improve the internal structure of code without changing its observable behavior, so that the next change becomes cheap and safe, and do it in steps small enough to verify and review.2122## When to use23- A feature or fix is blocked by code that is hard to understand or change ("make the change easy, then make the easy change").24- Review or analysis found smells worth fixing in actively changing code.25- Duplicated logic must be consolidated before it diverges further.2627## When not to use28- Only an assessment of problems is needed, no changes. Use `clean-code-review` or `tech-debt-assessment`.29- The code is not yet understood. Use `legacy-code-comprehension` first.30- The goal is speed, not structure. Use `performance-optimization`.3132## Inputs33Required:34- The code to refactor and the reason (the upcoming change or the pain it causes).3536Optional, improves quality:37- Existing tests, coding standards, language/framework version, constraints (public API must not change, no new dependencies).3839If there are no tests and none can be run, say so and start with characterization tests; never claim behavior is preserved without evidence.4041## Process421. State the goal in terms of the next change ("adding a discount type should touch one class").432. Identify the smells that block that goal (long function, duplicated conditional, feature envy, primitive obsession, shotgun surgery); ignore cosmetic ones.443. Check the safety net: which behaviors are covered by tests? Add characterization tests for uncovered paths, including odd current behavior (record it, do not fix it now).454. Choose named refactorings from the catalog vocabulary and order them from low risk (rename, extract variable, extract function) to structural (move function, replace conditional with polymorphism, split phase).465. Apply one refactoring per step; after each step the code compiles and tests pass. Keep behavior changes and bug fixes out of refactoring commits.476. Keep public contracts stable unless agreed; when a signature must change, use a parallel change (add new, migrate callers, remove old).487. Watch for semantic traps: evaluation order, side effects in moved code, null/empty handling, exception types, floating-point or rounding differences, thread safety of extracted state.498. After the sequence, compare before/after against the goal and remove scaffolding.509. Report each step with its refactoring name, suggested commit boundary and any behavior quirk discovered.5110. If the goal continues, suggest `unit-test-writing` where characterization tests were missing or `code-review` to review the refactored change.5253## Output format54```markdown55# Refactoring: <unit>56Goal: <what the next change should look like>57Safety net: <existing tests / added characterization tests>5859## Smells Addressed60| Smell | Location | Why it blocks the goal |6162## Steps63| # | Refactoring | Change | Tests green? |64|---|---|---|---|65| 1 | Extract Function | `applySeasonalDiscount` from lines .. | Yes |6667## Result68<final code or diff>6970## Discovered Behavior Quirks (not changed)71- ...72```7374## Quality checklist75- [ ] Observable behavior is unchanged, backed by tests that ran before and after.76- [ ] Each step is a named refactoring small enough to review in isolation.77- [ ] No bug fixes or features are mixed in; quirks are reported separately.78- [ ] Public API is unchanged or changed via parallel change.79- [ ] The result demonstrably makes the stated next change easier.80- [ ] Inferences are labeled `[ASSUMPTION]` and listed as assumptions or open questions; nothing unsupported is stated as fact.81- [ ] All checks pass; if any fails, revise the output and re-run this checklist before answering.8283## Common pitfalls84- "Big bang" rewrite labeled as refactoring. If it cannot be done in green steps, it is a rewrite and needs its own plan.85- Refactoring code nobody will change again. Prioritize by change frequency and upcoming work.86- Silently "fixing" odd behavior during extraction; callers may depend on it. Record it and fix in a separate change.8788## Example89Input: "calculatePrice has nested if/else for customer type and discount type; adding a new discount breaks things."9091Excerpt of output:921. Characterization tests: 12 combinations of customer type × discount type, including the current rounding of half cents (quirk recorded).932. Split Phase: separate "determine applicable discounts" from "apply discounts to price".943. Replace Conditional with Polymorphism: `Discount` interface with one implementation per type; new type = new class + registration.