| name | code-refactoring |
| description | Code refactoring patterns and techniques for improving code quality without changing behavior. Use when cleaning up legacy code, reducing complexity, extracting methods, removing duplication, improving maintainability, planning refactor steps, or matching code smells to safe refactoring patterns. |
Code Refactoring
Refactoring Principles
When to Refactor
- Before adding new features (make change easy, then make easy change)
- After getting tests passing (red-green-refactor)
- When you see code smells
- During code review feedback
When NOT to Refactor
- Without tests covering the code
- Under tight deadlines with no safety net
- Code that will be replaced soon
- When you don't understand what the code does
Common Code Smells
Long Methods
function processOrder(order: Order) {
}
function processOrder(order: Order) {
validateOrder(order);
const total = calculateTotal(order);
saveOrder(order, total);
notifyCustomer(order);
}
Deeply Nested Conditionals
function getDiscount(user: User, order: Order) {
if (user) {
if (user.isPremium) {
if (order.total > 100) {
if (order.items.length > 5) {
return 0.2;
}
}
}
}
return 0;
}
function getDiscount(user: User, order: Order) {
if (!user) return 0;
if (!user.isPremium) return 0;
if (order.total <= 100) return 0;
if (order.items.length <= 5) return 0;
return 0.2;
}
Primitive Obsession
function createUser(name: string, email: string, phone: string) {
if (!email.includes('@')) throw new Error('Invalid email');
}
class Email {
constructor(private value: string) {
if (!value.includes('@')) throw new Error('Invalid email');
}
toString() { return this.value; }
}
function createUser(name: string, email: Email, phone: Phone) {
}
Feature Envy
function calculateShipping(order: Order) {
const address = order.customer.address;
const weight = order.items.reduce((sum, i) => sum + i.weight, 0);
const distance = calculateDistance(address.zip);
return weight * distance * 0.01;
}
class Order {
calculateShipping() {
return this.totalWeight * this.customer.shippingDistance * 0.01;
}
}
Refactoring Techniques
Extract Method
function printReport(data: ReportData) {
const header = `Report: ${data.title}\nDate: ${data.date}\n${'='.repeat(40)}`;
console.log(header);
printHeader(data);
}
Replace Conditional with Polymorphism
function getArea(shape: Shape) {
switch (shape.type) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return shape.base * shape.height / 2;
}
}
interface Shape {
getArea(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
getArea() { return Math.PI * this.radius ** 2; }
}
class Rectangle implements Shape {
constructor( : , : ) {}
() { . * .; }
}
Introduce Parameter Object
function searchProducts(
query: string,
minPrice: number,
maxPrice: number,
category: string,
inStock: boolean,
sortBy: string,
sortOrder: string
) { ... }
interface SearchParams {
query: string;
priceRange: { min: number; max: number };
category?: string;
inStock?: boolean;
sort?: { by: string; order: 'asc' | 'desc' };
}
function searchProducts(params: SearchParams) { ... }
Replace Magic Numbers with Constants
if (user.age >= 18 && order.total >= 50) {
applyDiscount(order, 0.1);
}
const MINIMUM_AGE = 18;
const DISCOUNT_THRESHOLD = 50;
const STANDARD_DISCOUNT = 0.1;
if (user.age >= MINIMUM_AGE && order.total >= DISCOUNT_THRESHOLD) {
applyDiscount(order, STANDARD_DISCOUNT);
}
Safe Refactoring Process
- Ensure tests exist - Write tests if they don't
- Make small changes - One refactoring at a time
- Run tests after each change - Catch regressions immediately
- Commit frequently - Easy to revert if something breaks
- Review the diff - Make sure behavior hasn't changed
Refactoring Checklist