AgentSkillsCN

refactoring

对代码进行安全漏洞与OWASP问题的审计。当您需要审视代码安全性、排查潜在漏洞,或被要求对代码安全进行深度审计时,本技能将为您提供专业支持。

SKILL.md
--- frontmatter
name: refactoring
description: Improves code structure without changing behavior. Use when cleaning up code, reducing complexity, or when asked to refactor.

Refactoring

Golden Rule

Change behavior OR change structure, never both at once.

Workflow

  1. Ensure tests exist - Coverage before refactoring
  2. Make small changes - One refactoring at a time
  3. Run tests frequently - After each change
  4. Commit often - Easy to revert if needed

Common Refactorings

Extract Function

Before:

typescript
function processOrder(order: Order) {
  // 20 lines of validation
  // 30 lines of calculation
  // 15 lines of formatting
}

After:

typescript
function processOrder(order: Order) {
  validateOrder(order);
  const total = calculateTotal(order);
  return formatReceipt(order, total);
}

Replace Conditionals with Polymorphism

Before:

typescript
function getPrice(type: string) {
  if (type === 'regular') return basePrice;
  if (type === 'premium') return basePrice * 1.5;
  if (type === 'vip') return basePrice * 2;
}

After:

typescript
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:

typescript
if (user && user.isActive && user.subscription && user.subscription.isValid) {

After:

typescript
function hasValidSubscription(user: User): boolean {
  return user?.isActive && user?.subscription?.isValid;
}

if (hasValidSubscription(user)) {

Code Smells to Address

SmellRefactoring
Long functionExtract function
Duplicate codeExtract and reuse
Long parameter listIntroduce parameter object
Feature envyMove method to appropriate class
Primitive obsessionReplace with value object
Switch statementsReplace 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