.skills
skills / refactor

/refactor

Refatora código com explicações claras, identificando code smells e aplicando padrões comprovados.

willian
coding
v1.0.0
refactoring clean-code patterns code-quality
Ver todas

Instalação

$ curl -fsSL dotskills.dev/i/refactor | sh

SKILL.md

~/.claude/skills/refactor/SKILL.md

The Art of Refactoring

Refactoring is not rewriting—it's improving code without changing behavior. Each change should be small, safe, and purposeful.

Philosophy

Bad refactoring: "Let me rewrite this whole thing"
Good refactoring: "Let me improve this one aspect, verify it works, then continue"

The golden rule: Make the change easy, then make the easy change.


Before You Refactor

1. Understand the Code

  • What does this code do?
  • Why was it written this way?
  • What are the edge cases?
  • Are there tests?

2. Define Your Goal

What smell are you fixing?

  • Readability?
  • Performance?
  • Testability?
  • Duplication?

3. Ensure Safety

  • Do tests exist? If not, consider adding them first
  • Can you verify behavior hasn't changed?
  • Is this a good time? (not right before a release)

Common Code Smells

🔴 Critical Smells

God Object/Function

// ❌ Does everything
function processOrder(order) {
  // validate order (50 lines)
  // calculate prices (100 lines)
  // apply discounts (80 lines)
  // process payment (60 lines)
  // send emails (40 lines)
  // update inventory (30 lines)
}

// ✅ Single responsibility
function processOrder(order) {
  const validated = validateOrder(order);
  const priced = calculatePrices(validated);
  const discounted = applyDiscounts(priced);
  const paid = processPayment(discounted);
  notifyCustomer(paid);
  updateInventory(paid);
  return paid;
}

Deep Nesting

// ❌ Arrow code
if (user) {
  if (user.isActive) {
    if (user.hasPermission) {
      if (order.isValid) {
        // finally do something
      }
    }
  }
}

// ✅ Early returns (guard clauses)
if (!user) return;
if (!user.isActive) return;
if (!user.hasPermission) return;
if (!order.isValid) return;
// do something

🟠 Medium Smells

Magic Numbers/Strings

// ❌ What does 86400000 mean?
setTimeout(cleanup, 86400000);

// ✅ Self-documenting
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
setTimeout(cleanup, ONE_DAY_MS);

Duplicated Logic

// ❌ Same validation in 3 places
function createUser(data) {
  if (!data.email || !data.email.includes('@')) throw new Error('Invalid email');
  // ...
}
function updateUser(data) {
  if (!data.email || !data.email.includes('@')) throw new Error('Invalid email');
  // ...
}

// ✅ Extracted and reused
function validateEmail(email) {
  if (!email || !email.includes('@')) {
    throw new Error('Invalid email');
  }
}

Boolean Parameters

// ❌ What does 'true' mean?
createUser(data, true, false);

// ✅ Options object
createUser(data, { sendWelcomeEmail: true, requireVerification: false });

🟡 Minor Smells

Comments Explaining Bad Code

// ❌ Comment explains what code does
// Loop through users and check if active
for (let i = 0; i < users.length; i++) {
  if (users[i].status === 1) { // 1 means active
    // ...
  }
}

// ✅ Self-documenting code
const activeUsers = users.filter(user => user.isActive);
activeUsers.forEach(processUser);

Long Parameter Lists

// ❌ Too many parameters
function createEvent(name, date, location, organizer, capacity, price, category, isPublic) {}

// ✅ Object parameter
function createEvent({ name, date, location, organizer, capacity, price, category, isPublic }) {}

Refactoring Patterns

Extract Function

When a code block does one thing that can be named.

Inline Function

When a function body is as clear as its name.

Extract Variable

When an expression is complex or used multiple times.

Rename

When a name doesn't communicate purpose.

Replace Conditional with Polymorphism

When switch/if chains handle different types.

Replace Loop with Pipeline

When loops can be expressed as map/filter/reduce.


Refactoring Process

1. Small Steps

Make one change at a time. Verify. Commit. Repeat.

2. Run Tests

After every change, ensure tests pass.

3. No Behavior Changes

If tests fail, you've changed behavior—undo and try again.

4. Commit Often

Each refactoring step = one commit. Easy to revert if needed.


Output Format

## Refactoring: [file/function name]

### Analysis
[What the code does, why it needs refactoring]

### Identified Smells
1. [Smell name]: [Where and why it's a problem]
2. ...

### Proposed Changes
1. [Change description]
   - Before: [code snippet]
   - After: [code snippet]
   - Reason: [why this improves the code]

2. ...

### Risks
[What could go wrong, what tests should be run]

### Recommended Order
[Which changes to make first, dependencies between changes]

Flags

  • --aggressive: Apply more transformations, bigger changes
  • --dry-run: Only show proposed changes, don't modify files

What NOT to Do

  • ❌ Refactor and add features at the same time
  • ❌ Refactor without tests or verification
  • ❌ Make giant changes in one commit
  • ❌ Refactor just to match personal style
  • ❌ Refactor code you don't understand

Your Task

  1. Read and understand the specified code
  2. Identify code smells and improvement opportunities
  3. Prioritize by impact and risk
  4. Propose specific, incremental changes
  5. Explain the reasoning behind each change
  6. If not --dry-run, apply the changes carefully

Now refactor: $ARGUMENTS