agentsclimarketplace

Refactoring patterns

Skill fabioc-aloha/Alex_Skill_Mall/plugins/code-quality/refactoring-patterns

284 curated plugins for AI assistants across 16 categories: security, Azure, documentation, code quality, cloud infrastructure, and more. Works with GitHub Copilot. Drop into .github/skills/local/ and go.

Install
npx -y skills add fabioc-aloha/Alex_Skill_Mall --skill refactoring-patterns

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

One thing to look at

  • 3 stars3 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

What its author says it does

Copied from the file, not written here

Safe transformations — same behavior, better structure.

SKILL.md

6.3 KB, as published. Nobody here has run it

Refactoring Patterns Skill

Safe transformations — same behavior, better structure.

Golden Rule

Tests pass before AND after. Never refactor and add features in the same commit.

When to Refactor

TriggerAction
Feature is hard to addRefactor first, then add feature
Same bug twiceRefactor to prevent recurrence
"I don't understand"Refactor for clarity
Duplicate codeExtract and reuse
Long function (>30 lines)Extract logical units

When NOT to Refactor

  • No tests + time pressure
  • Code won't change again
  • Right before release (deadline pressure)
  • Should rewrite instead (>70% changes needed)
  • Exploratory/prototype code

Core Refactoring Moves

Extract Function

When a block does one logical thing, give it a name.

// Before
function processOrder(order: Order) {
  // Validate order
  if (!order.items.length) throw new Error('Empty order');
  if (!order.customer) throw new Error('No customer');
  if (order.total < 0) throw new Error('Invalid total');
  
  // Calculate tax
  const taxRate = order.region === 'EU' ? 0.20 : 0.10;
  const tax = order.total * taxRate;
  
  // Apply discount
  const discount = order.customer.isPremium ? 0.15 : 0;
  const finalTotal = order.total + tax - (order.total * discount);
  
  return finalTotal;
}

// After
function processOrder(order: Order) {
  validateOrder(order);
  const tax = calculateTax(order);
  const discount = calculateDiscount(order);
  return order.total + tax - discount;
}

function validateOrder(order: Order): void {
  if (!order.items.length) throw new Error('Empty order');
  if (!order.customer) throw new Error('No customer');
  if (order.total < 0) throw new Error('Invalid total');
}

function calculateTax(order: Order): number {
  const taxRate = order.region === 'EU' ? 0.20 : 0.10;
  return order.total * taxRate;
}

function calculateDiscount(order: Order): number {
  return order.customer.isPremium ? order.total * 0.15 : 0;
}

Extract Variable

Name complex expressions to reveal intent.

// Before
if (user.age >= 18 && user.country === 'US' && !user.banned && user.emailVerified) {
  allowAccess();
}

// After
const isAdult = user.age >= 18;
const isUSResident = user.country === 'US';
const isInGoodStanding = !user.banned && user.emailVerified;
const canAccess = isAdult && isUSResident && isInGoodStanding;

if (canAccess) {
  allowAccess();
}

Rename for Intent

Names should reveal what, not how.

// Before
const d = new Date().getTime() - start;
const arr = users.filter(u => u.a);

// After
const elapsedMs = new Date().getTime() - startTime;
const activeUsers = users.filter(user => user.isActive);

Replace Conditional with Polymorphism

// Before
function calculatePay(employee: Employee): number {
  switch (employee.type) {
    case 'hourly':
      return employee.hours * employee.rate;
    case 'salaried':
      return employee.salary / 12;
    case 'commission':
      return employee.sales * employee.commissionRate + employee.basePay;
  }
}

// After
interface PayStrategy {
  calculate(employee: Employee): number;
}

class HourlyPay implements PayStrategy {
  calculate(emp: Employee): number {
    return emp.hours * emp.rate;
  }
}

class SalariedPay implements PayStrategy {
  calculate(emp: Employee): number {
    return emp.salary / 12;
  }
}

class CommissionPay implements PayStrategy {
  calculate(emp: Employee): number {
    return emp.sales * emp.commissionRate + emp.basePay;
  }
}

Guard Clauses (Replace Nested Conditionals)

// Before
function getPayAmount(employee: Employee): number {
  let result: number;
  if (employee.isSeparated) {
    result = 0;
  } else {
    if (employee.isRetired) {
      result = employee.pension;
    } else {
      result = employee.salary;
    }
  }
  return result;
}

// After
function getPayAmount(employee: Employee): number {
  if (employee.isSeparated) return 0;
  if (employee.isRetired) return employee.pension;
  return employee.salary;
}

Code Smells → Refactoring

SmellSymptomsRefactoring
Long function>30 lines, multiple comments explaining sectionsExtract Function
Long parameter list>4 parametersIntroduce Parameter Object
Duplicate codeSame logic in 2+ placesExtract Function, Pull Up Method
Feature envyMethod uses another object's data more than its ownMove Function
Large classClass does too many thingsExtract Class
Primitive obsessionUsing primitives instead of small objectsReplace Primitive with Object
Data clumpsSame group of variables appear togetherIntroduce Parameter Object
Switch statementsType-based conditionalsReplace Conditional with Polymorphism
Temporary fieldField only used sometimesExtract Class
Refused bequestSubclass ignores inherited methodsReplace Inheritance with Delegation

Refactor vs Rewrite Decision

RefactorRewrite
Core design is soundFundamental design is wrong
Tests exist and passCode is untestable
<30% of code changes>70% of code changes
Incremental improvementComplete replacement
Low riskHigher risk
Keep shipping featuresPause feature work

Safe Refactoring Workflow

1. Commit current state (safety net)
2. Run all tests (establish baseline)
3. Make ONE small change
4. Run tests
5. Commit with descriptive message
6. Repeat steps 3-5

Never: Refactor while adding features. Refactor OR feature, never both.

IDE Refactoring Support

Most refactorings are automated in VS Code:

RefactoringVS Code Shortcut
Rename SymbolF2
Extract FunctionCtrl+Shift+R → Extract Function
Extract VariableCtrl+Shift+R → Extract Variable
Inline VariableCtrl+Shift+R → Inline Variable
Move to FileCtrl+Shift+R → Move to new file

Prefer IDE refactoring over manual edits — fewer mistakes, automatic reference updates.

Keep looking

Skills are one crate of 328,083. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.