| name | refactor |
| description | Restructure code to improve quality without changing behavior |
| allowed-tools | ["Read","Write","Edit","Bash","Grep","Glob"] |
Refactoring Skill
Improve code structure and quality while preserving behavior.
Name
han-core:refactor - Restructure code to improve quality without changing behavior
Synopsis
/refactor [arguments]
Core Principle
Tests are your safety net. Never refactor without tests.
The Refactoring Cycle
- Ensure tests exist and pass
- Make ONE small change
- Run tests (must still pass)
- Commit (keep changes isolated)
- Repeat
Each step must be reversible. If tests fail, revert and try smaller change.
Pre-Refactoring Checklist
STOP if any of these are false:
If no tests exist:
- Add tests first
- Verify tests pass
- THEN refactor
When to Refactor
Code Smells That Suggest Refactoring
Readability issues:
- Long functions (> 50 lines)
- Deep nesting (> 3 levels)
- Unclear naming
- Magic numbers
- Complex conditionals
Maintainability issues:
- Duplication (same code in multiple places)
- God classes (too many responsibilities)
- Feature envy (method uses another class more than its own)
- Data clumps (same groups of parameters passed around)
Complexity issues:
- Cyclomatic complexity > 10
- Too many dependencies
- Tightly coupled code
- Difficult to test
When NOT to Refactor
- No tests exist (add tests first)
- Under deadline pressure (defer to later)
- Code works and is readable (don't over-engineer)
- Changing external behavior (that's not refactoring, that's a feature/fix)
- Right before release (too risky)
Classic Refactorings
Extract Function
Problem: Function does too many things
function processOrder(order: Order) {
if (!order.items || order.items.length === 0) {
throw new Error('Empty order')
}
if (!order.customer || !order.customer.email) {
throw new Error('Invalid customer')
}
let subtotal = 0
for (const item of order.items) {
subtotal += item.price * item.quantity
}
const tax = subtotal * 0.08
const shipping = subtotal > 50 ? 0 : 9.99
const total = subtotal + tax + shipping
return database.save({
...order,
subtotal,
tax,
shipping,
total
})
}
function processOrder(order: Order) {
validateOrder(order)
totals = (order)
(order, totals)
}
(): {
(!order. || order.. === ) {
()
}
(!order. || !order..) {
()
}
}
() {
subtotal = order..(
sum + item. * item.,
)
tax = subtotal *
shipping = subtotal > ? :
total = subtotal + tax + shipping
{ subtotal, tax, shipping, total }
}
() {
database.({ ...order, ...totals })
}
Benefits: Each function has single responsibility, easier to test, easier to understand
Extract Variable
Problem: Complex expression that's hard to understand
if (user.age >= 18 && user.country === 'US' && !user.banned && user.verified) {
}
const isAdult = user.age >= 18
const isUSResident = user.country === 'US'
const hasGoodStanding = !user.banned && user.verified
const canPurchase = isAdult && isUSResident && hasGoodStanding
if (canPurchase) {
}
Benefits: Self-documenting, easier to debug, easier to modify
Inline Function/Variable
Problem: Unnecessary indirection that doesn't add clarity
function getTotal(order: Order) {
return calculateTotalAmount(order)
}
function calculateTotalAmount(order: Order) {
return order.subtotal + order.tax
}
function getTotal(order: Order) {
return order.subtotal + order.tax
}
When to inline: Abstraction doesn't add value, makes code harder to follow
Rename
Problem: Unclear or misleading names
function proc(d: any) {
const r = d.x * d.y
return r
}
function calculateArea(dimensions: Dimensions) {
const area = dimensions.width * dimensions.height
return area
}
Benefits: Code is self-documenting, no need to guess what variables mean
Replace Magic Number with Named Constant
Problem: Unexplained numbers in code
const tax = subtotal * 0.08
const shipping = subtotal > 50 ? 0 : 9.99
const TAX_RATE = 0.08
const FREE_SHIPPING_THRESHOLD = 50
const STANDARD_SHIPPING_COST = 9.99
const tax = subtotal * TAX_RATE
const shipping = subtotal > FREE_SHIPPING_THRESHOLD ? 0 : STANDARD_SHIPPING_COST
Remove Duplication
Problem: Same code in multiple places
function formatUserName(user: User) {
return `${user.firstName} ${user.lastName}`.trim()
}
function formatAdminName(admin: Admin) {
return `${admin.firstName} ${admin.lastName}`.trim()
}
function formatAuthorName(author: Author) {
return `${author.firstName} ${author.lastName}`.trim()
}
function formatFullName(person: { firstName: string; lastName: string }) {
return `${person.firstName} ${person.lastName}`.trim()
}
formatFullName(user)
formatFullName(admin)
formatFullName(author)
Simplify Conditional
Problem: Complex nested if/else
function getShippingCost(order: Order) {
if (order.total > 100) {
return 0
} else {
if (order.items.length > 5) {
return 5.99
} else {
if (order.weight > 10) {
return 15.99
} else {
return 9.99
}
}
}
}
function getShippingCost(order: Order) {
if (order.total > 100) return 0
if (order.items.length > 5) return 5.99
if (order.weight > 10) return 15.99
return 9.99
}
const SHIPPING_RULES = [
{ : o. > , : },
{ : o.. > , : },
{ : o. > , : },
]
() {
rule = .( r.(order))
rule?. ??
}
Replace Conditional with Polymorphism
Problem: Type checks scattered throughout code
function calculatePrice(item: Item) {
if (item.type === 'book') {
return item.basePrice * 0.9
} else if (item.type === 'electronics') {
return item.basePrice * 1.15
} else if (item.type === 'clothing') {
return item.basePrice
}
}
interface Item {
calculatePrice(): number
}
class Book implements Item {
calculatePrice() {
return this.basePrice * 0.9
}
}
class Electronics implements Item {
calculatePrice() {
return this.basePrice * 1.15
}
}
class {
() {
.
}
}
price = item.()
Split Function
Problem: Function tries to do too many things
function processPayment(payment: Payment) {
if (!payment.amount || payment.amount <= 0) {
throw new Error('Invalid amount')
}
if (!payment.method) {
throw new Error('Payment method required')
}
const fee = payment.amount * 0.029 + 0.30
const total = payment.amount + fee
const record = database.save({
amount: payment.amount,
fee,
total,
method: payment.method,
timestamp: Date.now()
})
notificationService.send({
user: payment.user,
message: `Payment of $${total} processed`
})
return record
}
function processPayment(: ) {
(payment)
totals = (payment)
record = (payment, totals)
(payment., totals.)
record
}
Refactoring Golden Rules
Safety first:
- Tests exist and pass before starting
- Make one change at a time
- Run tests after each change
- Behavior must remain unchanged
- Commit after each successful refactoring
Refactoring Workflow
Step-by-Step Process
npm test
npm test
git add .
git commit -m "refactor: extract validateOrder function"
If Tests Fail After Refactoring
git reset --hard HEAD
Refactoring Strategies
The Boy Scout Rule
"Leave code better than you found it"
When touching code for any reason:
- Fix obvious issues you see
- Improve naming
- Extract complex expressions
- Add missing tests
- Remove commented code
Small improvements accumulate
Preparatory Refactoring
Before adding feature, refactor to make it easy
1. Need to add feature
2. Current code structure makes it hard
3. Refactor first to make space
4. Then add feature in clean code
Quote: "Make the change easy, then make the easy change"
Opportunistic Refactoring
Fix things you notice while working
- Fixing bug? Clean up surrounding code
- Adding feature? Improve structure
- Reading code? Fix confusing names
Planned Refactoring
Dedicated time to improve code health
- Tech debt tickets
- Refactoring sprints
- Clean-up sessions
Refactoring Safety Checklist
Before every change:
After every change:
If tests fail:
Common Refactoring Pitfalls
Refactoring Without Tests
Risk: Change behavior without noticing
Solution: Add tests first, then refactor
Too Many Changes at Once
Risk: Hard to debug if something breaks
Solution: One refactoring at a time, commit frequently
Changing Behavior
Risk: It's not refactoring if behavior changes
Solution: Tests must still pass, functionality unchanged
Over-Engineering
Risk: More complex after "refactoring"
Solution: Simpler is better, don't add unnecessary abstraction
Refactoring Under Pressure
Risk: Mistakes due to rushing
Solution: Defer to when you have time to do it right
Measuring Refactoring Success
Good refactoring results in:
- Easier to understand
- Easier to modify
- Easier to test
- Fewer lines of code (usually)
- Lower complexity
- Same or better performance
- All tests still pass
If any test fails, it wasn't successful refactoring
Output Format
After refactoring:
## Refactoring: [Brief description]
### Before
[Description of code smell or issue]
### Changes Made
- [Change 1 with reasoning]
- [Change 2 with reasoning]
- [Change 3 with reasoning]
### After
[How the code is better now]
### Verification
[Evidence that behavior unchanged - use proof-of-work skill]
- All tests pass: [test output]
- No functionality changed
- Code is more [readable/maintainable/simple]
Examples
When the user says:
- "This function is too long and hard to understand"
- "Clean up this messy code"
- "Remove duplication between these modules"
- "Simplify this nested if/else logic"
- "Break this god class into smaller pieces"
Tools
Automated refactoring tools:
- IDE refactoring commands (safe)
- Rename variable/function (safe)
- Extract method (safe)
- Move file (safe)
Manual refactoring:
- Make small changes
- Test frequently
- Commit after each change
- Use version control as safety net
Integration with Other Skills
- boy-scout-rule - Leave code better than found
- simplicity-principles - KISS, YAGNI, simple is better
- solid-principles - Single Responsibility, etc.
- structural-design-principles - Composition, encapsulation
- test-driven-development - Add tests if missing
- proof-of-work - Verify tests still pass
- code-review - Review refactored code
Remember
- Tests first - No refactoring without tests
- Small steps - One change at a time
- Test after each step - Must stay green
- Commit frequently - Each safe change gets a commit
- Behavior unchanged - If behavior changes, it's not refactoring
Refactoring is about improving structure without changing what the code does.