Skip to content
refactoring-patterns logo

Refactoring Patterns

refactoring-patterns

Apply when improving code structure without changing behavior: reducing duplication, simplifying complexity, or improving readability.

SKILL.md

Full skill instructions

When to Use

Apply when improving code structure without changing behavior: reducing duplication, simplifying complexity, or improving readability.

Patterns

Pattern 1: Extract Function

// Source: https://refactoring.guru/​extract-method
// BEFORE
function processOrder(order: Order) {
  // Validate
  if (!order.items.length) throw new Error('Empty');
  if (!order.customer) throw new Error('No customer');

  // Calculate total
  let total = 0;
  for (const item of order.items) {
    total += item.price * item.quantity;
  }
  total *= 1.1; // Tax

  // Save
  db.orders.create({ ...order, total });
}

// AFTER
function processOrder(order: Order) {
  validateOrder(order);
  const total = calculateTotal(order.items);
  saveOrder(order, total);
}

function validateOrder(order: Order) { /​* ... */ }
function calculateTotal(items: Item[]) { /​* ... */ }
function saveOrder(order: Order, total: number) { /​* ... */ }

Pattern 2: Replace Conditional with Polymorphism

// Source: https://refactoring.guru/​replace-conditional-with-polymorphism
// BEFORE
function getPrice(item: Item) {
  switch (item.type) {
    case 'book': return item.basePrice * 0.9;
    case 'electronics': return item.basePrice * 1.1;
    case 'food': return item.basePrice;
  }
}

// AFTER
interface PricingStrategy {
  calculate(basePrice: number): number;
}

const strategies: Record<string, PricingStrategy> = {
  book: { calculate: (p) => p * 0.9 },
  electronics: { calculate: (p) => p * 1.1 },
  food: { calculate: (p) => p },
};

function getPrice(item: Item) {
  return strategies[item.type].calculate(item.basePrice);
}

Pattern 3: Introduce Parameter Object

// Source: https://refactoring.guru/​introduce-parameter-object
// BEFORE
function searchProducts(
  query: string,
  minPrice: number,
  maxPrice: number,
  category: string,
  inStock: boolean,
  sortBy: string,
  page: number
) { /​* ... */ }

// AFTER
interface SearchParams {
  query: string;
  priceRange?: { min: number; max: number };
  category?: string;
  inStock?: boolean;
  sortBy?: string;
  page?: number;
}

function searchProducts(params: SearchParams) { /​* ... */ }

Pattern 4: Replace Magic Numbers

// Source: https://refactoring.guru/​replace-magic-number-with-symbolic-constant
// BEFORE
if (user.age >= 18) { /​* ... */ }
setTimeout(fn, 86400000);

// AFTER
const LEGAL_AGE = 18;
const ONE_DAY_MS = 24 * 60 * 60 * 1000;

if (user.age >= LEGAL_AGE) { /​* ... */ }
setTimeout(fn, ONE_DAY_MS);

Pattern 5: Guard Clauses (Early Return)

// Source: https://refactoring.guru/​replace-nested-conditional-with-guard-clauses
// BEFORE
function getPayment(employee: Employee) {
  let result;
  if (employee.isSeparated) {
    result = separatedAmount();
  } else {
    if (employee.isRetired) {
      result = retiredAmount();
    } else {
      result = normalAmount();
    }
  }
  return result;
}

// AFTER
function getPayment(employee: Employee) {
  if (employee.isSeparated) return separatedAmount();
  if (employee.isRetired) return retiredAmount();
  return normalAmount();
}

Pattern 6: Compose Method

// Source: https://refactoring.guru/​compose-method
// Goal: Each function does ONE thing at ONE level of abstraction
function processUser(userData: UserInput) {
  const validated = validateUserData(userData);
  const normalized = normalizeUserData(validated);
  const enriched = enrichWithDefaults(normalized);
  return saveUser(enriched);
}

Anti-Patterns

  • Refactoring without tests - Tests must pass before AND after
  • Big bang refactor - Small incremental changes
  • Premature abstraction - Wait for duplication (Rule of 3)
  • Refactoring during feature work - Separate commits

Verification Checklist

  • Tests pass before refactoring
  • Tests pass after refactoring
  • Behavior unchanged
  • Each commit is atomic (compilable)
  • Code review before merge

More Other skills

Delegate independent tasks to specialized agents working concurrently with isolated context.

295.4K 206.3K
View

Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.

179.7K 100.1K
View

Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors/fonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.

179.7K 89.5K
View

A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).

179.7K 76.1K
View

Fundamental design principles for writing maintainable, testable Python code.

40.2K 21.9K
View

Modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first strategies.

40.2K 20K
View

Generate Playwright tests from scenarios using interactive browser exploration and validation.

39.7K 18.2K
View

Modern React state management with Redux Toolkit, Zustand, Jotai, and React Query for every state category.

40.2K 14.7K
View

GDPR-compliant data handling with consent management, data subject rights, and privacy controls.

40.2K 14.3K
View

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.

40.2K 13.5K
View

Detailed multi-file refactor planning with safety checks and rollback guidance.

39.7K 13K
View