Skip to main content
ClaudeWave
Skill85 estrellas del repoactualizado 3mo ago

code-refactoring-assistant

Suggest and apply code refactorings to improve readability, maintainability, and code quality. Use this skill when improving existing code structure, eliminating code smells, applying design patterns, simplifying complex logic, extracting duplicated code, renaming for clarity, or preparing code for new features. Provides specific before/after examples, explains benefits, identifies risks, and ensures behavior preservation through tests.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/code-refactoring-assistant && cp -r /tmp/code-refactoring-assistant/skills/code-refactoring-assistant ~/.claude/skills/code-refactoring-assistant
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Code Refactoring Assistant

Systematically improve code structure and quality through targeted refactorings. Identifies opportunities, suggests improvements, and applies changes while preserving behavior.

## Core Capabilities

### 1. Code Smell Detection

Identify refactoring opportunities:
- **Long methods/functions** - Functions doing too much
- **Large classes** - Classes with too many responsibilities
- **Duplicate code** - Repeated logic across codebase
- **Long parameter lists** - Functions with many parameters
- **Primitive obsession** - Using primitives instead of objects
- **Feature envy** - Methods using other classes more than their own
- **Data clumps** - Same group of data appearing together
- **Switch statements** - Complex conditionals that could be polymorphic

### 2. Structural Refactorings

Improve code organization:
- **Extract Method** - Pull out code into new function
- **Extract Class** - Split class responsibilities
- **Inline Method/Variable** - Remove unnecessary indirection
- **Move Method/Field** - Relocate to appropriate class
- **Rename** - Improve naming clarity
- **Change Function Signature** - Update parameters
- **Introduce Parameter Object** - Group parameters into object
- **Replace Conditional with Polymorphism** - Use inheritance/interfaces

### 3. Simplification Refactorings

Reduce complexity:
- **Decompose Conditional** - Simplify complex if/else
- **Consolidate Conditional** - Combine related conditions
- **Remove Dead Code** - Delete unused code
- **Simplify Boolean Expression** - Make logic clearer
- **Replace Magic Number with Constant** - Named constants
- **Replace Nested Conditional with Guard Clauses** - Early returns
- **Replace Loop with Pipeline** - Use functional operations

### 4. Generalization Refactorings

Improve abstraction:
- **Extract Interface** - Define contracts
- **Extract Superclass** - Pull up common behavior
- **Replace Type Code with Class** - Use objects not constants
- **Replace Conditional with Strategy** - Pluggable behavior
- **Form Template Method** - Define algorithm skeleton
- **Replace Constructor with Factory** - Flexible object creation

## Refactoring Workflow

### Step 1: Identify Refactoring Opportunity

Recognize code that needs improvement:

**Questions to ask:**
- Is this function/method too long? (>20-30 lines)
- Does this class have too many responsibilities?
- Is this code duplicated elsewhere?
- Are these names clear and descriptive?
- Is this logic overly complex?
- Would a design pattern help here?

**Example identification:**
```python
# Long method doing multiple things
def process_user_order(user_id, items, payment_info, shipping_address):  # 150 lines!
    # Validate user
    # Validate items
    # Calculate prices
    # Apply discounts
    # Process payment
    # Update inventory
    # Create shipment
    # Send emails
    # Update analytics
    # ...

# Opportunity: Extract Method refactoring
# This should be broken into focused functions
```

### Step 2: Choose Appropriate Refactoring

Select the right transformation:

**Refactoring catalog:**

| Code Smell | Refactoring Solution |
|------------|---------------------|
| Long Method | Extract Method, Replace Temp with Query |
| Large Class | Extract Class, Extract Subclass |
| Long Parameter List | Introduce Parameter Object, Preserve Whole Object |
| Duplicate Code | Extract Method, Pull Up Method, Form Template Method |
| Complex Conditional | Decompose Conditional, Replace Conditional with Polymorphism |
| Primitive Obsession | Replace Type Code with Class, Introduce Value Object |
| Feature Envy | Move Method, Extract Method |
| Data Clumps | Extract Class, Introduce Parameter Object |

**Example selection:**
```python
# Problem: Long Parameter List
def create_user(first_name, last_name, email, phone, street, city, state, zip_code, country):
    pass

# Solution: Introduce Parameter Object
# Create Address and User classes to group related data
```

### Step 3: Plan the Refactoring

Ensure safe transformation:

**Pre-refactoring checklist:**
- [ ] Code is under version control
- [ ] Tests exist and pass
- [ ] Understand current behavior completely
- [ ] Identify all callers/dependencies
- [ ] Plan small, incremental steps
- [ ] Know how to verify correctness

**Refactoring plan example:**
```markdown
Refactoring: Extract Class for Address information

Current state:
- User class has 8 address-related fields
- Address logic scattered across User methods

Steps:
1. Create new Address class
2. Add address fields to Address
3. Add Address field to User
4. Update User constructor to accept Address
5. Update all address-related methods
6. Run tests after each step
7. Remove old address fields from User

Risk: Medium (many callers to update)
Estimated time: 1-2 hours
```

### Step 4: Apply Refactoring Incrementally

Make changes in small, safe steps:

**Guidelines:**
- Make one change at a time
- Run tests after each step
- Commit after each successful refactoring
- If tests fail, revert and try smaller steps
- Keep working code compiling/running

**Example incremental approach:**
```python
# Step 1: Extract method (just one piece)
def process_order(order):
    # Before: All inline
    total = 0
    for item in order.items:
        total += item.price * item.quantity
    # ... rest of function

# Step 1a: Extract just the calculation
def calculate_total(items):
    total = 0
    for item in items:
        total += item.price * item.quantity
    return total

def process_order(order):
    total = calculate_total(order.items)
    # ... rest of function

# Run tests → Pass → Commit

# Step 2: Extract next piece (validation)
# Step 3: Extract next piece (payment)
# etc.
```

### Step 5: Verify and Document

Confirm behavior preservation:

**Verification steps:**
1. All existing tests pass
2. No new warnings or errors
3. Code review for correctness
4. Manual testing of critical paths
5. Performance not degraded

**Documentation:**
```python
# Doc
abstract-domain-explorerSkill

Applies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.

abstract-invariant-generatorSkill

Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.

abstract-state-analyzerSkill

Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.

abstract-trace-summarizerSkill

Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.

acsl-annotation-assistantSkill

Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.

agent-browserSkill

CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

ambiguity-detectorSkill

Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.

api-design-assistantSkill

Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.