opencode/skills/refactoring-code/SKILL.md
Improve code structure while preserving behavior with test verification. Use when cleaning up code, reducing duplication, simplifying complexity, or reorganizing modules.
npx skillsauth add third774/dotfiles refactoring-codeInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
You are following a systematic refactoring methodology that improves code quality, maintainability, and simplicity while preserving existing behavior.
Core Principle: Refactoring changes structure, not functionality. Safety and clarity are more important than elegance.
BEHAVIOR MUST BE PRESERVED
Tests must verify behavior, not implementation
If you change what the code does (not just how it does it), you're not refactoring—you're rewriting.
any types when possibleYou MUST complete each phase before proceeding to the next.
Copy this checklist and track your progress:
Refactoring Progress:
- [ ] Phase 1: Understand Current Behavior
- [ ] Read existing code thoroughly
- [ ] Check usage across codebase
- [ ] Document current behavior
- [ ] Phase 2: Verify Test Coverage (CRITICAL)
- [ ] Behavior-driven tests exist and pass
- [ ] Tests cover main workflows and edge cases
- [ ] Tests don't depend on implementation details
- [ ] Phase 3: Identify Issues
- [ ] Issues documented with locations
- [ ] Issues categorized by type and severity
- [ ] Root cause understood for each issue
- [ ] Phase 4: Plan Refactoring
- [ ] Broken into small, verifiable steps
- [ ] Each step has verification criteria
- [ ] Dependencies between steps identified
- [ ] Phase 5: Execute & Verify
- [ ] All planned changes implemented
- [ ] All tests pass
- [ ] No new type errors or warnings
- [ ] Behavior verified unchanged
Objective: Know exactly what the code does before changing how it does it.
Read existing code thoroughly
Check usage across codebase
Document current behavior
Phase 1 Complete When:
Objective: Ensure behavior-driven tests exist that will catch regressions.
BEFORE refactoring, ensure tests verify BEHAVIOR (what users see/do), NOT implementation:
✅ Good - Behavior-driven tests:
// Tests user-observable behavior
test('displays error message when API returns 404', async () => {
server.use(
http.get('/api/users', () => new HttpResponse(null, { status: 404 }))
);
render(<UserList />);
expect(await screen.findByText(/user not found/i)).toBeInTheDocument();
});
❌ Bad - Implementation-detail tests:
// Tests internal state/functions - breaks during refactoring
test('sets error state when fetch fails', () => {
const wrapper = shallow(<UserList />);
wrapper.instance().handleError(new Error('404'));
expect(wrapper.state('error')).toBe('404');
});
Test Quality Checklist:
If tests are missing or test implementation details:
writing-tests skill)Why this matters: Unit tests checking internal state break during refactoring even when behavior is unchanged. Behavior-driven tests prove the feature works before and after.
Phase 2 Complete When:
Objective: Systematically catalog what needs improvement.
Common refactoring opportunities:
| Issue Type | Indicators | Impact |
|------------|-----------|---------|
| Complexity | Deep nesting (>3 levels), long functions (>50 lines), many parameters (>4) | Hard to understand, error-prone |
| Duplication | Copy-pasted code, repeated patterns, similar logic in multiple places | Maintenance burden, inconsistent fixes |
| Poor Naming | Unclear variables (x, data, temp), misleading names, inconsistent terminology | Cognitive overhead |
| Type Safety Gaps | any types, missing types, type assertions, implicit any | Runtime errors, poor IDE support |
| Performance Issues | Unnecessary re-renders, inefficient algorithms (O(n²) when O(n) possible), large bundle size | Slow UX, high resource usage |
| Pattern Violations | Inconsistent with project conventions, outdated patterns | Team confusion, tech debt |
Analysis checklist:
Phase 3 Complete When:
Objective: Create a safe, incremental execution plan.
Create todo list for multi-step refactorings (use TodoWrite tool)
Prioritize changes by impact and risk
Consider backward compatibility
Plan verification steps
Example refactoring breakdown:
**Large task:** Extract user authentication logic into reusable hook
**Breakdown:**
1. Create new hook file with basic structure
2. Move authentication state management to hook
3. Move login/logout handlers to hook
4. Extract token refresh logic
5. Replace inline logic in components with hook calls
6. Remove old duplicated code
7. Add tests for hook
Phase 4 Complete When:
Objective: Make changes safely with continuous verification.
Execution principles:
Make one change at a time
Run tests after each change
Check TypeScript compilation
tsc --noEmit or equivalentVerify behavior unchanged
Verification checklist per step:
npm test or equivalent)If something breaks:
systematic-debugging skill to investigatePhase 5 Complete When:
If you catch yourself:
ALL of these mean: STOP. Reassess your approach.
For TypeScript/React projects, see references/react-typescript.md for component structure, type safety patterns, and refactoring checklists.
| Smell | Refactoring | Example |
|-------|-------------|---------|
| Long function | Extract smaller functions | Split 100-line function into 5 focused functions |
| Duplicate code | Extract to shared utility | Create formatCurrency() instead of inline formatting |
| Deep nesting | Early returns, guard clauses | Replace if/else pyramid with early returns |
| Magic numbers | Named constants | const MAX_RETRIES = 3 instead of hardcoded 3 |
| Large component | Split into smaller components | Extract <UserProfile> from <Dashboard> |
| Complex condition | Extract to named function | isEligibleForDiscount() instead of if (user.age > 65 && user.isPremium && ...) |
| Primitive obsession | Create type/interface | type Email = string with validation instead of raw strings |
| Long parameter list | Parameter object | Pass { user, options, config } instead of 8 parameters |
This skill requires using:
Complementary skills:
You've refactored enough when:
Don't refactor further if:
When proposing refactorings:
Explain what problems you're solving
Show before/after comparisons
Highlight risks and breaking changes
Suggest incremental steps for large refactorings
Challenge your own assumptions
Remember: The goal of refactoring is to make future changes easier, not to make code perfect.
data-ai
Extract captions and transcripts from YouTube videos for agent context. Tries manual subtitles, then auto-generated, then falls back to audio transcription via Whisper. Use when a user provides a YouTube URL and wants to understand, summarize, reference, or search video content.
tools
Official skill for XcodeBuildMCP. Use when doing iOS/macOS/watchOS/tvOS/visionOS work (build, test, run, debug, log, UI automation).
development
Write behavior-focused tests following Testing Trophy model with real dependencies, avoiding common anti-patterns like testing mocks and polluting production code. Use when writing new tests, reviewing test quality, or improving test coverage.
data-ai
Create professional Mermaid diagrams with proper styling and visual hierarchy. Use when creating flowcharts, sequence diagrams, state machines, class diagrams, or architecture visualizations.