agentleFS
nisarthnisarth/claude-skills-store/skills/engineering/refactoring/SKILL.md

refactoring

Skill1 starsChanged 7 months agoMITView on GitHub

Plan and execute code refactoring. Extract methods, decompose classes, apply design patterns, reduce complexity, and maintain backward compatibility throughout. Trigger with "refactor this", "this code is messy", "simplify this", "extract a function", "reduce complexity", "apply design pattern", or when the user wants to restructure code without changing behavior.

58 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use ci-cd, dependency-management and 7 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • JohnJBorenSkill

    ci-cd

    CI/CD pipeline design, GitHub Actions, testing automation, and deployment strategies

    Also in 5 projects that use this

  • dkprogSkill

    dependency-management

    Apply when wiring dependencies, integrating external services, or designing interfaces between modules. Ensures loose coupling through dependency injection, interface segregation, and proper abstraction boundaries.

    Also in 3 projects that use this

  • javalenciacaiSkill

    multi-agent-orchestration

    Design and coordinate multi-agent systems where specialized agents work together to solve complex problems. Covers agent communication, task delegation, workflow orchestration, and result aggregation. Use when building coordinated agent teams, complex workflows, or systems requiring specialized expertise across domains.

    Also in 3 projects that use this

  • harrissohail6Skill

    database-design

    Database schema design and SQL best practices. Use when designing tables, writing queries, or optimizing database performance.

    Also in 5 projects that use this

  • klauswgSkill

    performance

    Optimize web performance for faster loading and better user experience. Use when asked to "speed up my site", "optimize performance", "reduce load time", "fix slow loading", "improve page speed", or "performance audit".

    Also in 7 projects that use this

  • AWSSkill

    planning

    Discovers user intent and generates a structured, step-by-step plan for model customization workflows. This skill must always be activated alongside any other skill when the user's request relates to model customization — including fine-tuning, training, building, customizing, reviewing data, or getting advice on approach, regardless of domain. Do not skip this skill even if the immediate ask is narrow (e.g., reviewing data format or a single workflow step), because planning discovers the full scope of work needed. Also activate when the user wants to resume, continue, or modify an existing plan.

    Also in 6 projects that use this

The file

Show its rules and text

We split this skill into the rules it gives an agent

20 rules. 0 are common, 20 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 53 edited versions we read keep these.

  • 20

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Read the target code and assess its current state:

    line 33
  2. Distinctive:

    Check test coverage: Run tests and check coverage.

    line 37
  3. Distinctive:

    Understand the domain: Read surrounding code and comments to understand business context.

    line 39
  4. Distinctive:

    Create a step-by-step plan before making any changes:

    line 55
  5. Distinctive:

    Ensure test coverage: Write missing tests for the code being refactored.

    line 57
  6. Distinctive:

    Order changes by risk: Start with the safest, most mechanical refactorings.

    line 58
  7. Distinctive:

    Use composition: the original class delegates to the new classes.

    line 127
  8. Distinctive:

    Run tests to verify behavior is unchanged.

    line 186
  9. Distinctive:

    Commit the change with a descriptive message.

    line 188
  10. Distinctive:

    If tests fail after a refactoring step, revert and investigate before proceeding.

    line 190
  11. Distinctive:

    After all refactoring steps are complete:

    line 194
  12. Distinctive:

    Run the full test suite.

    line 196
  13. Distinctive:

    Check for unused imports, dead code, or orphaned files created during refactoring.

    line 197
  14. Distinctive:

    Verify that public APIs (function signatures, exports, endpoints) have not changed unless intended.

    line 198
  15. Distinctive:

    Action: Read the function, identify logical sections, extract each section into a named function with clear parameters and return values, …

    line 244
  16. Distinctive:

    Never refactor without tests.

    line 257
  17. Distinctive:

    Commit after each successful refactoring step.

    line 260
  18. Distinctive:

    Do not over-abstract. Extracting a function used only once may reduce readability rather than improve it.

    line 262
  19. Distinctive:

    Use the IDE or editor's refactoring tools when available (rename symbol, extract method) as they handle all references automatically.

    line 264
  20. Distinctive:

    Consider readability from the perspective of someone seeing the code for the first time.

    line 265

“Common” is measured: kept by at least 6 in 10 of the 53 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Refactoring

Plan and execute safe code refactoring. Identify code smells, apply proven refactoring patterns, maintain backward compatibility, and verify correctness with tests throughout the process.

Workflow

Step 1: Analyze the Current Code

Read the target code and assess its current state:

  • Read the file/module: Understand what the code does, not just how it looks.
  • Identify code smells: Long methods, deep nesting, duplicated code, feature envy, data clumps.
  • Check test coverage: Run tests and check coverage. If coverage is low, write tests first.
  • Map dependencies: What calls this code? What does it call? Use grep to find usages.
  • Understand the domain: Read surrounding code and comments to understand business context.

Code smell checklist:

  • Functions longer than 30 lines
  • Functions with more than 4 parameters
  • Cyclomatic complexity above 10
  • Deeply nested conditionals (3+ levels)
  • Duplicated code blocks (3+ similar blocks)
  • God classes (classes doing too many things)
  • Feature envy (method uses another class's data more than its own)
  • Primitive obsession (using primitives instead of value objects)
  • Shotgun surgery (one change requires edits in many places)
  • Long switch/if-else chains on the same discriminator

Step 2: Plan the Refactoring

Create a step-by-step plan before making any changes:

  1. Ensure test coverage: Write missing tests for the code being refactored.
  2. Order changes by risk: Start with the safest, most mechanical refactorings.
  3. Keep changes small: Each step should be independently verifiable.
  4. Maintain backward compatibility: Public interfaces should not change unless explicitly planned.

Common refactoring patterns:

Extract Method — Pull a block of code into a named function:

# Before
def process_order(order):
    # validate
    if not order.items:
        raise ValueError("Empty order")
    if order.total < 0:
        raise ValueError("Negative total")
    # calculate tax
    tax = order.total * 0.08
    if order.state == "OR":
        tax = 0
    # ... more code

# After
def process_order(order):
    validate_order(order)
    tax = calculate_tax(order)
    # ... more code

def validate_order(order):
    if not order.items:
        raise ValueError("Empty order")
    if order.total < 0:
        raise ValueError("Negative total")

def calculate_tax(order):
    if order.state == "OR":
        return 0
    return order.total * 0.08

Replace Conditional with Polymorphism:

# Before
def calculate_shipping(order):
    if order.type == "standard":
        return order.weight * 0.5
    elif order.type == "express":
        return order.weight * 1.5 + 10
    elif order.type == "overnight":
        return order.weight * 3.0 + 25

# After
class ShippingCalculator:
    _strategies = {
        "standard": lambda w: w * 0.5,
        "express": lambda w: w * 1.5 + 10,
        "overnight": lambda w: w * 3.0 + 25,
    }

    @classmethod
    def calculate(cls, order):
        strategy = cls._strategies.get(order.type)
        if not strategy:
            raise ValueError(f"Unknown shipping type: {order.type}")
        return strategy(order.weight)

Decompose Class — Split a god class into focused classes:

  • Identify groups of related fields and methods.
  • Extract each group into its own class.
  • Use composition: the original class delegates to the new classes.

Replace Magic Values with Constants:

// Before
if (user.role === 3) { ... }
setTimeout(retry, 30000);

// After
const ROLE_ADMIN = 3;
const RETRY_DELAY_MS = 30_000;
if (user.role === ROLE_ADMIN) { ... }
setTimeout(retry, RETRY_DELAY_MS);

Introduce Parameter Object — Group related parameters:

// Before
function createUser(name: string, email: string, age: number,
                    street: string, city: string, zip: string) { ... }

// After
interface Address { street: string; city: string; zip: string; }
interface CreateUserInput { name: string; email: string; age: number; address: Address; }
function createUser(input: CreateUserInput) { ... }

Flatten Nested Conditionals — Use early returns (guard clauses):

// Before
function getDiscount(user) {
  if (user) {
    if (user.isPremium) {
      if (user.yearsActive > 5) {
        return 0.3;
      } else {
        return 0.15;
      }
    } else {
      return 0.05;
    }
  }
  return 0;
}

// After
function getDiscount(user) {
  if (!user) return 0;
  if (!user.isPremium) return 0.05;
  if (user.yearsActive > 5) return 0.3;
  return 0.15;
}

Step 3: Execute in Small Steps

For each refactoring step:

  1. Make the change (one pattern at a time).
  2. Run tests to verify behavior is unchanged.
  3. Review the diff to confirm it is purely structural.
  4. Commit the change with a descriptive message.

If tests fail after a refactoring step, revert and investigate before proceeding.

Step 4: Verify and Clean Up

After all refactoring steps are complete:

  • Run the full test suite.
  • Check for unused imports, dead code, or orphaned files created during refactoring.
  • Verify that public APIs (function signatures, exports, endpoints) have not changed unless intended.
  • Review the final diff as a whole to ensure the refactoring achieved its goals.

Output Format

## Refactoring Plan

### Current State
**File**: <path>
**Issues identified**:
- <code smell 1 with location>
- <code smell 2 with location>
**Test coverage**: <percentage or description>

### Refactoring Steps

#### Step 1: <refactoring pattern name>
**Target**: <function/class/block>
**Rationale**: <why this improves the code>
**Before**:
```<language>
<current code>

After:

<refactored code>

Verification: Run <test command>

Step 2: <next pattern>

...

Summary

  • Lines of code: <before> -> <after>
  • Cyclomatic complexity: <before> -> <after>
  • Functions extracted: <count>
  • Test coverage: <before> -> <after>

Risks and Mitigations

  • <risk 1>: <mitigation>

## Examples

**User**: "This function is 200 lines long, help me break it up"
**Action**: Read the function, identify logical sections, extract each section into a named function with clear parameters and return values, verify with tests at each step.

**User**: "Refactor this class to use the strategy pattern"
**Action**: Identify the conditional logic that varies, define a strategy interface, implement concrete strategies, replace conditionals with strategy dispatch, verify behavior is unchanged.

**User**: "Simplify this deeply nested code"
**Action**: Apply guard clauses to flatten nesting, extract helper functions for complex conditions, replace nested callbacks with async/await if applicable.

**User**: "This module has a lot of duplicated code"
**Action**: Identify duplicated blocks, extract shared logic into reusable functions, parameterize the differences, update all call sites, verify with tests.

## Best Practices

- Never refactor without tests. If tests do not exist, write them first. The tests are what guarantee behavior is preserved.
- Make one type of change at a time. Do not rename variables in the same commit as extracting methods. Keep each step verifiable.
- Refactoring should not change behavior. If you find a bug while refactoring, fix it in a separate commit so the fix is visible in the history.
- Commit after each successful refactoring step. Small commits make it easy to bisect if something goes wrong later.
- Name extracted functions based on WHAT they do (intent), not HOW they do it (implementation).
- Do not over-abstract. Extracting a function used only once may reduce readability rather than improve it. The rule of three is a good guideline: abstract when you see the same pattern three times.
- Preserve the public API unless the refactoring explicitly aims to change it. Internal restructuring should be invisible to callers.
- Use the IDE or editor's refactoring tools when available (rename symbol, extract method) as they handle all references automatically.
- Consider readability from the perspective of someone seeing the code for the first time. Clever code that is hard to follow defeats the purpose of refactoring.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.