refactoring-patterns
Patterns for safe behavior-preserving refactoring — extract, rename, move, simplify — with test-baseline and rollback guidance. Trigger on refactor or restructure requests.
What this skill does
# Refactoring Patterns Skill
Systematic refactoring with safety checks and verification.
## When to Use
- Extracting methods, classes, or modules
- Renaming identifiers safely across codebase
- Moving code between files or modules
- Simplifying complex code
- Modernizing legacy patterns
## Reference Documents
- [Extract Patterns](./references/extract-patterns.md) - Extract method/class/module patterns
- [Rename Patterns](./references/rename-patterns.md) - Safe renaming across codebase
- [Move Patterns](./references/move-patterns.md) - Moving code between files/modules
- [Simplify Patterns](./references/simplify-patterns.md) - Reducing complexity patterns
## Core Principles
### 1. Never Refactor Without Tests
```markdown
BEFORE refactoring:
1. Ensure tests exist for code being changed
2. Run tests to confirm they pass
3. Note coverage percentage
DURING refactoring:
4. Run tests after each small change
5. Keep changes atomic and reversible
AFTER refactoring:
6. Run full test suite
7. Verify coverage didn't decrease
```
### 2. Small, Incremental Changes
```
BAD: One massive PR that changes everything
GOOD: Series of small PRs, each working state
Commit 1: Add new class
Commit 2: Add tests for new class
Commit 3: Migrate first usage
Commit 4: Migrate remaining usages
Commit 5: Remove old code
```
### 3. Preserve Behavior
Refactoring changes structure, not behavior.
```python
# BEFORE
def calculate_total(items):
total = 0
for item in items:
total += item.price * item.quantity
return total
# AFTER (same behavior, different structure)
def calculate_total(items):
return sum(item.price * item.quantity for item in items)
```
## Refactoring Workflow
### Step 1: Identify the Smell
| Code Smell | Refactoring |
|------------|-------------|
| Long method | Extract Method |
| Large class | Extract Class |
| Duplicated code | Extract Method/Class |
| Long parameter list | Introduce Parameter Object |
| Data clumps | Extract Class |
| Primitive obsession | Replace Primitive with Object |
| Switch statements | Replace with Polymorphism |
| Parallel inheritance | Collapse Hierarchy |
### Step 2: Ensure Test Coverage
```bash
# Check current coverage
pytest --cov=module_to_refactor --cov-report=term-missing
# If coverage < 80%, add tests first
pytest tests/test_module.py -v
```
### Step 3: Apply Refactoring
Execute refactoring in small steps:
```markdown
Extract Method Example:
1. [ ] Identify code to extract
2. [ ] Create new method with extracted code
3. [ ] Replace original code with method call
4. [ ] Run tests
5. [ ] Commit
```
### Step 4: Verify
```bash
# Run tests
pytest
# Check for regressions
git diff HEAD~1 --stat
# Review changes
git diff HEAD~1 path/to/file.py
```
## Common Refactorings
### Extract Method
```python
# BEFORE
def process_order(order):
# Validate order
if not order.items:
raise ValueError("Order has no items")
if order.total <= 0:
raise ValueError("Order total must be positive")
# Calculate discount
discount = 0
if order.customer.is_premium:
discount = order.total * 0.1
# Process payment
payment = Payment(amount=order.total - discount)
payment.process()
# AFTER
def process_order(order):
validate_order(order)
discount = calculate_discount(order)
process_payment(order, discount)
def validate_order(order):
if not order.items:
raise ValueError("Order has no items")
if order.total <= 0:
raise ValueError("Order total must be positive")
def calculate_discount(order):
if order.customer.is_premium:
return order.total * 0.1
return 0
def process_payment(order, discount):
payment = Payment(amount=order.total - discount)
payment.process()
```
### Extract Class
```python
# BEFORE
class Order:
def __init__(self):
self.items = []
self.shipping_address_line1 = ""
self.shipping_address_line2 = ""
self.shipping_city = ""
self.shipping_state = ""
self.shipping_zip = ""
self.shipping_country = ""
def format_shipping_address(self):
return f"{self.shipping_address_line1}\n{self.shipping_city}, {self.shipping_state}"
# AFTER
class Address:
def __init__(self, line1, line2, city, state, zip_code, country):
self.line1 = line1
self.line2 = line2
self.city = city
self.state = state
self.zip_code = zip_code
self.country = country
def format(self):
return f"{self.line1}\n{self.city}, {self.state}"
class Order:
def __init__(self):
self.items = []
self.shipping_address = None
```
### Rename
```bash
# Safe rename using IDE/tools
# In VS Code: F2 on symbol
# In PyCharm: Shift+F6
# Manual rename with verification
grep -rn "old_name" --include="*.py"
# Replace all occurrences
sed -i 's/old_name/new_name/g' path/to/files/*.py
# Run tests
pytest
```
## Safety Checklist
Before refactoring:
- [ ] Tests exist and pass
- [ ] Coverage is adequate (>80%)
- [ ] Changes are scoped and understood
- [ ] Rollback plan exists
During refactoring:
- [ ] Make one change at a time
- [ ] Run tests after each change
- [ ] Commit working states
After refactoring:
- [ ] All tests pass
- [ ] Coverage maintained or improved
- [ ] No behavior changes (unless intentional)
- [ ] Code review completed
## Quick Reference
| Refactoring | When to Use | Risk |
|-------------|-------------|------|
| Rename | Unclear names | Low |
| Extract Method | Long methods | Low |
| Inline Method | Unnecessary indirection | Low |
| Extract Class | Large class | Medium |
| Move Method | Method in wrong class | Medium |
| Replace Conditional with Polymorphism | Complex conditionals | High |
| Change Method Signature | API changes | High |
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.