QA Refactoring Safety
Use this skill to refactor safely: preserve behavior, reduce risk, and keep CI green while improving maintainability and delivery speed.
Defaults: baseline first, smallest safe step next, and proof via tests/contracts/observability instead of intuition.
Quick Start (10 Minutes)
- If key context is missing, ask for: what must not change (invariants), risk level (money/auth/migrations/concurrency), deployment constraints, and the smallest boundary that can be protected by tests.
- Confirm baseline:
main green; reproduce the behavior you must preserve.
- Choose a boundary: API surface, module boundary, DB boundary, or request handler.
- Add a safety net: characterization/contract/integration tests at that boundary.
- Refactor in micro-steps: one behavior-preserving change per commit/PR chunk.
- Prove: run the smallest relevant suite locally, then full CI; keep failures deterministic.
Core QA (Default)
Safe Refactor Loop (Behavior First)
- Establish baseline: get
main green; reproduce the behavior you must preserve.
- Define invariants: inputs/outputs, error modes, permissions, data shape, performance budgets.
- Add a safety net: write characterization/contract/integration tests around the boundary you will touch.
- Create seams: introduce injection points/adapters to isolate side effects and external dependencies.
- Refactor in micro-steps: one behavior-preserving change at a time; keep diffs reviewable.
- Prove: run the smallest relevant suite locally, then full CI; keep failures debuggable and deterministic.
- Ship safely: use canary/dark launch/feature flags when refactors touch production-critical paths.
Risk Levels (Choose Safety Net)
| Risk |
Examples |
Minimum required safety net |
| Low |
rename, extract method, formatting-only |
unit tests + lint/type checks |
| Medium |
moving logic across modules, dependency inversion |
unit + integration/contract tests at boundary |
| High |
auth/permission paths, concurrency, migrations, money/data-loss paths |
integration + contract tests, observability checks, canary + rollback plan |
Test Strategy for Refactors
- Prefer contract and integration tests around boundaries to preserve behavior.
- Use snapshots/golden masters only when outputs are stable and reviewed (avoid "approve everything" loops).
- For invariants, consider property-based tests or table-driven cases (inputs, edge cases, error modes).
- Avoid making E2E/UI tests the primary safety net for refactors; keep most safety below the UI.
- For flaky areas: fix determinism first (seeds, time, ordering, network) before trusting results.
CI Economics and Debugging Ergonomics
- Keep refactor PRs small and reviewable; avoid refactor + feature in one PR.
- Require failure artifacts for tests guarding refactors (logs, trace IDs, deterministic seeds, repro steps).
- Reduce diff noise: isolate formatting-only changes (or apply formatting repo-wide once with buy-in).
- Keep
git bisect viable: avoid mixed "mechanical + semantic" changes unless necessary.
Do / Avoid
Do:
- Add missing tests before refactoring high-risk areas.
- Add guardrails (linters, type checks, contract checks, static analysis/security checks) so refactors don't silently break interfaces.
- Prefer "branch by abstraction" / adapters when you need to swap implementations safely.
Avoid:
- Combining large structural refactors with behavior changes.
- Using flaky E2E as the primary safety net for refactors.
Quick Reference
| Task |
Tool/Pattern |
Command/Approach |
When to Use |
| Long method (>50 lines) |
Extract Method |
Split into smaller functions |
Single method does too much |
| Large class (>300 lines) |
Split Class |
Create focused single-responsibility classes |
God object doing too much |
| Duplicated code |
Extract Function/Class |
DRY principle |
Same logic in multiple places |
| Complex conditionals |
Replace Conditional with Polymorphism |
Use inheritance/strategy pattern |
Switch statements on type |
| Long parameter list |
Introduce Parameter Object |
Create DTO/config object |
Functions with >3 parameters |
| Legacy code modernization |
Characterization Tests + Strangler Fig |
Write tests first, migrate incrementally |
No tests, old codebase |
| Automated quality gates |
ESLint, SonarQube, Prettier |
npm run lint, CI/CD pipeline |
Prevent quality regression |
| Technical debt tracking |
SonarQube, CodeClimate |
Track trends + hotspots |
Prioritize refactoring work |
Decision Tree: Refactoring Strategy
Code issue: [Refactoring Scenario]
├─ Code Smells Detected?
│ ├─ Duplicated code? → Extract method/function
│ ├─ Long method (>50 lines)? → Extract smaller methods
│ ├─ Large class (>300 lines)? → Split into focused classes
│ ├─ Long parameter list? → Parameter object
│ └─ Feature envy? → Move method closer to data
│
├─ Legacy Code (No Tests)?
│ ├─ High risk? → Write characterization tests first
│ ├─ Large rewrite needed? → Strangler Fig (incremental migration)
│ ├─ Unknown behavior? → Characterization tests + small refactors
│ └─ Production system? → Canary deployments + monitoring
│
├─ Quality Standards?
│ ├─ New project? → Setup linter + formatter + quality gates
│ ├─ Existing project? → Add pre-commit hooks + CI checks
│ ├─ Complexity issues? → Set cyclomatic complexity limits (<10)
│ └─ Technical debt? → Track in register, 20% sprint capacity
Related Skills
Scope Boundaries (Handoffs)
- Pure test flake cleanup (timers, ordering, retries):
../qa-debugging/SKILL.md
- Pure performance tuning (SQL, indexing, query plans):
../data-sql-optimization/SKILL.md
- Architecture redesign decisions (service boundaries, eventing):
../software-architecture-design/SKILL.md
Operational Deep Dives
Shared Foundation
Skill-Specific
See references/operational-patterns.md for detailed refactoring catalogs, automated quality gates, technical debt playbooks, and legacy modernization steps.
Templates
Use copy-paste templates in assets/ for checklists and quality-gate configs:
- Refactoring: assets/process/refactoring-checklist.md, assets/process/code-review-quality.md
- Technical debt: assets/tracking/tech-debt-register.md
- Quality gates: assets/quality-gates/javascript/eslint-config.js, assets/quality-gates/platform-agnostic/sonarqube-setup.md
Resources
Use deep-dive guides in references/ (load only what you need):
- Operational Patterns: references/operational-patterns.md - Core refactoring catalogs, quality gates, and legacy modernization
- Refactoring Catalog: references/refactoring-catalog.md
- Code Smells Guide: references/code-smells-guide.md
- Technical Debt Management: references/tech-debt-management.md
- Legacy Code Modernization: references/legacy-code-strategies.md
- Characterization Testing: references/characterization-testing.md - Golden master and approval testing patterns
- Strangler Fig Migration: references/strangler-fig-migration.md - Incremental legacy migration strategies
- Automated Refactoring Tools: references/automated-refactoring-tools.md - Codemods, AST transforms, and IDE refactoring
Optional: AI / Automation
Do:
- Use AI to propose mechanical refactors (rename/extract/move) only when you can prove behavior preservation via tests and contracts.
- Use AI to summarize diffs and risk hotspots; verify by running targeted characterization tests.
- Prefer tool-assisted refactors (IDE/compiler-aware, codemods) over freeform text edits when available.
Avoid:
- Accepting refactors that change behavior without an explicit requirement and regression tests.
- Letting AI "fix tests" by weakening assertions to make CI green.
See data/sources.json for curated external references.
Fact-Checking
- Use web search/web fetch to verify current external facts, versions, pricing, deadlines, regulations, or platform behavior before final answers.
- Prefer primary sources; report source links and dates for volatile information.
- If web access is unavailable, state the limitation and mark guidance as unverified.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: qa-refactoring3description: Safe refactoring with behavior preservation. Use when reducing technical debt, applying strangler migrations, or tightening CI guardrails. Use when this capability is needed.4---56# QA Refactoring Safety78Use this skill to refactor safely: preserve behavior, reduce risk, and keep CI green while improving maintainability and delivery speed.910Defaults: baseline first, smallest safe step next, and proof via tests/contracts/observability instead of intuition.1112## Quick Start (10 Minutes)1314- If key context is missing, ask for: what must not change (invariants), risk level (money/auth/migrations/concurrency), deployment constraints, and the smallest boundary that can be protected by tests.15- Confirm baseline: `main` green; reproduce the behavior you must preserve.16- Choose a boundary: API surface, module boundary, DB boundary, or request handler.17- Add a safety net: characterization/contract/integration tests at that boundary.18- Refactor in micro-steps: one behavior-preserving change per commit/PR chunk.19- Prove: run the smallest relevant suite locally, then full CI; keep failures deterministic.2021## Core QA (Default)2223### Safe Refactor Loop (Behavior First)2425- Establish baseline: get `main` green; reproduce the behavior you must preserve.26- Define invariants: inputs/outputs, error modes, permissions, data shape, performance budgets.27- Add a safety net: write characterization/contract/integration tests around the boundary you will touch.28- Create seams: introduce injection points/adapters to isolate side effects and external dependencies.29- Refactor in micro-steps: one behavior-preserving change at a time; keep diffs reviewable.30- Prove: run the smallest relevant suite locally, then full CI; keep failures debuggable and deterministic.31- Ship safely: use canary/dark launch/feature flags when refactors touch production-critical paths.3233### Risk Levels (Choose Safety Net)3435| Risk | Examples | Minimum required safety net |36|------|----------|-----------------------------|37| Low | rename, extract method, formatting-only | unit tests + lint/type checks |38| Medium | moving logic across modules, dependency inversion | unit + integration/contract tests at boundary |39| High | auth/permission paths, concurrency, migrations, money/data-loss paths | integration + contract tests, observability checks, canary + rollback plan |4041### Test Strategy for Refactors4243- Prefer contract and integration tests around boundaries to preserve behavior.44- Use snapshots/golden masters only when outputs are stable and reviewed (avoid "approve everything" loops).45- For invariants, consider property-based tests or table-driven cases (inputs, edge cases, error modes).46- Avoid making E2E/UI tests the primary safety net for refactors; keep most safety below the UI.47- For flaky areas: fix determinism first (seeds, time, ordering, network) before trusting results.4849### CI Economics and Debugging Ergonomics5051- Keep refactor PRs small and reviewable; avoid refactor + feature in one PR.52- Require failure artifacts for tests guarding refactors (logs, trace IDs, deterministic seeds, repro steps).53- Reduce diff noise: isolate formatting-only changes (or apply formatting repo-wide once with buy-in).54- Keep `git bisect` viable: avoid mixed "mechanical + semantic" changes unless necessary.5556### Do / Avoid5758Do:5960- Add missing tests before refactoring high-risk areas.61- Add guardrails (linters, type checks, contract checks, static analysis/security checks) so refactors don't silently break interfaces.62- Prefer "branch by abstraction" / adapters when you need to swap implementations safely.6364Avoid:6566- Combining large structural refactors with behavior changes.67- Using flaky E2E as the primary safety net for refactors.6869## Quick Reference7071| Task | Tool/Pattern | Command/Approach | When to Use |72| ---- | ------------ | ---------------- | ----------- |73| Long method (>50 lines) | Extract Method | Split into smaller functions | Single method does too much |74| Large class (>300 lines) | Split Class | Create focused single-responsibility classes | God object doing too much |75| Duplicated code | Extract Function/Class | DRY principle | Same logic in multiple places |76| Complex conditionals | Replace Conditional with Polymorphism | Use inheritance/strategy pattern | Switch statements on type |77| Long parameter list | Introduce Parameter Object | Create DTO/config object | Functions with >3 parameters |78| Legacy code modernization | Characterization Tests + Strangler Fig | Write tests first, migrate incrementally | No tests, old codebase |79| Automated quality gates | ESLint, SonarQube, Prettier | `npm run lint`, CI/CD pipeline | Prevent quality regression |80| Technical debt tracking | SonarQube, CodeClimate | Track trends + hotspots | Prioritize refactoring work |8182## Decision Tree: Refactoring Strategy8384```text85Code issue: [Refactoring Scenario]86 ├─ Code Smells Detected?87 │ ├─ Duplicated code? → Extract method/function88 │ ├─ Long method (>50 lines)? → Extract smaller methods89 │ ├─ Large class (>300 lines)? → Split into focused classes90 │ ├─ Long parameter list? → Parameter object91 │ └─ Feature envy? → Move method closer to data92 │93 ├─ Legacy Code (No Tests)?94 │ ├─ High risk? → Write characterization tests first95 │ ├─ Large rewrite needed? → Strangler Fig (incremental migration)96 │ ├─ Unknown behavior? → Characterization tests + small refactors97 │ └─ Production system? → Canary deployments + monitoring98 │99 ├─ Quality Standards?100 │ ├─ New project? → Setup linter + formatter + quality gates101 │ ├─ Existing project? → Add pre-commit hooks + CI checks102 │ ├─ Complexity issues? → Set cyclomatic complexity limits (<10)103 │ └─ Technical debt? → Track in register, 20% sprint capacity104```105106## Related Skills107108- Debugging production issues: [qa-debugging](../qa-debugging/SKILL.md)109- Code review process and checklists: [software-code-review](../software-code-review/SKILL.md)110- New architecture design from scratch: [software-architecture-design](../software-architecture-design/SKILL.md)111- Test strategy and coverage planning: [qa-testing-strategy](../qa-testing-strategy/SKILL.md)112113## Scope Boundaries (Handoffs)114115- Pure test flake cleanup (timers, ordering, retries): `../qa-debugging/SKILL.md`116- Pure performance tuning (SQL, indexing, query plans): `../data-sql-optimization/SKILL.md`117- Architecture redesign decisions (service boundaries, eventing): `../software-architecture-design/SKILL.md`118119## Operational Deep Dives120121### Shared Foundation122123- [../software-clean-code-standard/references/clean-code-standard.md](../software-clean-code-standard/references/clean-code-standard.md) - Canonical clean code rules (`CC-*`) for citation124- Legacy playbook: [../software-clean-code-standard/references/code-quality-operational-playbook.md](../software-clean-code-standard/references/code-quality-operational-playbook.md) - `RULE-01`–`RULE-13`, decision trees, and operational procedures125- [../software-clean-code-standard/references/refactoring-operational-checklist.md](../software-clean-code-standard/references/refactoring-operational-checklist.md) - Refactoring smell-to-action mapping, safe refactoring guardrails126- [../software-clean-code-standard/references/working-effectively-with-legacy-code-operational-checklist.md](../software-clean-code-standard/references/working-effectively-with-legacy-code-operational-checklist.md) - Seams, characterization tests, incremental migration patterns127128### Skill-Specific129130See [references/operational-patterns.md](references/operational-patterns.md) for detailed refactoring catalogs, automated quality gates, technical debt playbooks, and legacy modernization steps.131132## Templates133134Use copy-paste templates in `assets/` for checklists and quality-gate configs:135136- Refactoring: [assets/process/refactoring-checklist.md](assets/process/refactoring-checklist.md), [assets/process/code-review-quality.md](assets/process/code-review-quality.md)137- Technical debt: [assets/tracking/tech-debt-register.md](assets/tracking/tech-debt-register.md)138- Quality gates: [assets/quality-gates/javascript/eslint-config.js](assets/quality-gates/javascript/eslint-config.js), [assets/quality-gates/platform-agnostic/sonarqube-setup.md](assets/quality-gates/platform-agnostic/sonarqube-setup.md)139140## Resources141142Use deep-dive guides in `references/` (load only what you need):143144- **Operational Patterns**: [references/operational-patterns.md](references/operational-patterns.md) - Core refactoring catalogs, quality gates, and legacy modernization145- **Refactoring Catalog**: [references/refactoring-catalog.md](references/refactoring-catalog.md)146- **Code Smells Guide**: [references/code-smells-guide.md](references/code-smells-guide.md)147- **Technical Debt Management**: [references/tech-debt-management.md](references/tech-debt-management.md)148- **Legacy Code Modernization**: [references/legacy-code-strategies.md](references/legacy-code-strategies.md)149- **Characterization Testing**: [references/characterization-testing.md](references/characterization-testing.md) - Golden master and approval testing patterns150- **Strangler Fig Migration**: [references/strangler-fig-migration.md](references/strangler-fig-migration.md) - Incremental legacy migration strategies151- **Automated Refactoring Tools**: [references/automated-refactoring-tools.md](references/automated-refactoring-tools.md) - Codemods, AST transforms, and IDE refactoring152153## Optional: AI / Automation154155Do:156157- Use AI to propose mechanical refactors (rename/extract/move) only when you can prove behavior preservation via tests and contracts.158- Use AI to summarize diffs and risk hotspots; verify by running targeted characterization tests.159- Prefer tool-assisted refactors (IDE/compiler-aware, codemods) over freeform text edits when available.160161Avoid:162163- Accepting refactors that change behavior without an explicit requirement and regression tests.164- Letting AI "fix tests" by weakening assertions to make CI green.165166See [data/sources.json](data/sources.json) for curated external references.167168## Fact-Checking169170- Use web search/web fetch to verify current external facts, versions, pricing, deadlines, regulations, or platform behavior before final answers.171- Prefer primary sources; report source links and dates for volatile information.172- If web access is unavailable, state the limitation and mark guidance as unverified.173174---175> Converted and distributed by [TomeVault](https://tomevault.io/claim/vasilyu1983) — claim your Tome and manage your conversions.176<!-- tomevault:4.0:skill_md:2026-04-11 -->