refactoring
Refactoring
Golden Rule
Change behavior OR change structure, never both at once.
Workflow
- Ensure tests exist - Coverage before refactoring
- Make small changes - One refactoring at a time
- Run tests frequently - After each change
- Commit often - Easy to revert if needed
Common Refactorings
Extract Function
Before:
function processOrder(order: Order) {
// 20 lines of validation
// 30 lines of calculation
// 15 lines of formatting
}
After:
function processOrder(order: Order) {
validateOrder(order);
const total = calculateTotal(order);
return formatReceipt(order, total);
}
Replace Conditionals with Polymorphism
Before:
function getPrice(type: string) {
if (type === 'regular') return basePrice;
if (type === 'premium') return basePrice * 1.5;
if (type === 'vip') return basePrice * 2;
}
After:
interface PricingStrategy {
getPrice(basePrice: number): number;
}
const strategies: Record<string, PricingStrategy> = {
regular: { getPrice: (p) => p },
premium: { getPrice: (p) => p * 1.5 },
vip: { getPrice: (p) => p * 2 },
};
Simplify Conditionals
Before:
if (user && user.isActive && user.subscription && user.subscription.isValid) {
After:
function hasValidSubscription(user: User): boolean {
return user?.isActive && user?.subscription?.isValid;
}
if (hasValidSubscription(user)) {
Code Smells to Address
| Smell | Refactoring |
|---|---|
| Long function | Extract function |
| Duplicate code | Extract and reuse |
| Long parameter list | Introduce parameter object |
| Feature envy | Move method to appropriate class |
| Primitive obsession | Replace with value object |
| Switch statements | Replace with polymorphism |
When NOT to Refactor
- No test coverage (add tests first)
- Under time pressure (technical debt is ok short-term)
- Code is about to be replaced
- Refactoring scope is unclear
More from mrwogu/promptscript
promptscript
>-
12committing
Creates well-structured git commits following conventional commit format. Use when committing changes, preparing commits, or when asked to commit code.
1pull-requesting
Creates well-structured pull requests with clear descriptions. Use when creating PRs, preparing changes for review, or when asked to open a pull request.
1code-reviewing
Reviews code for bugs, security issues, and quality improvements. Use when reviewing pull requests, checking code quality, or when asked to review changes.
1documenting
Creates clear, maintainable documentation for code and APIs. Use when writing README files, API docs, code comments, or when asked to document code.
1testing-code
Writes comprehensive tests following AAA pattern. Use for unit and integration tests.
1