agentleFS
derheissenbergderheissenberg/applicaiton/.cursor/skills/refactoring/SKILL.md

Refactoring

Skill2 starsChanged 6 months agoMITView on GitHub

This skill should be used when the user asks to "refactor code", "rename function", "extract method", "reduce complexity", "migrate code", "code migration", "modernize code", "split class", "move code", or mentions code restructuring and refactoring operations.

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 9 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

  • MicrosoftSkill

    error-handling

    统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。

    Also in 7 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

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

    Find all references: Search for all usages

    line 19
  2. Distinctive:

    Perform rename: Update all occurrences

    line 22
  3. Distinctive:

    Verify: Run tests, check imports

    line 23
  4. Distinctive:

    Update docstrings mentioning the old name

    line 40
  5. Distinctive:

    Update comments referencing the name

    line 41
  6. Distinctive:

    Consider deprecation period for public APIs

    line 44
  7. Distinctive:

    Create new function with clear name

    line 62
  8. Distinctive:

    Add tests for new function

    line 64
  9. Distinctive:

    Create compatibility layer: If gradual migration

    line 214
  10. Distinctive:

    Migrate in phases: Start with low-risk areas

    line 215
  11. Distinctive:

    Maintain tests: Ensure behavior preserved

    line 216
  12. Distinctive:

    Ensure test coverage: Add tests if missing

    line 239
  13. Distinctive:

    Run tests: Verify green baseline

    line 240
  14. Distinctive:

    Run tests again: Verify still green

    line 242
  15. Distinctive:

    When refactoring public APIs:

    line 318
  16. Distinctive:

    Add deprecation warnings first

    line 320
  17. Distinctive:

    Remove after deprecation period

    line 323
  18. Distinctive:

    When refactoring data models:

    line 327
  19. Distinctive:

    Test migrations on copy of data

    line 330
  20. Distinctive:

    test-coverage skill: Ensure test coverage

    line 348

“Common” is measured: kept by at least 6 in 10 of the 52 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

Comprehensive refactoring skill for safe code restructuring, migrations, and modernization.

Core Capabilities

Safe Renaming

Rename identifiers across the codebase:

Rename workflow:

  1. Find all references: Search for all usages
  2. Identify scope: Module-local, package-wide, or public API
  3. Check dependencies: External code that might break
  4. Perform rename: Update all occurrences
  5. Verify: Run tests, check imports

Search patterns:

# Find all references to a function
grep -rn "function_name" --include="*.py"

# Find class usages
grep -rn "ClassName" --include="*.py"

# Find imports
grep -rn "from .* import.*function_name" --include="*.py"

Renaming considerations:

  • Update docstrings mentioning the old name
  • Update comments referencing the name
  • Update configuration files
  • Update tests
  • Consider deprecation period for public APIs

Method Extraction

Extract code into separate functions:

When to extract:

  • Code block is too long (> 20 lines)
  • Code is duplicated elsewhere
  • Code has a clear single purpose
  • Code can be tested independently

Extraction process:

  1. Identify the code block to extract
  2. Determine inputs (parameters)
  3. Determine outputs (return values)
  4. Create new function with clear name
  5. Replace original code with function call
  6. Add tests for new function

Before:

def process_order(order):
    # Validate order (candidate for extraction)
    if not order.items:
        raise ValueError("Empty order")
    if order.total < 0:
        raise ValueError("Invalid total")
    for item in order.items:
        if item.quantity <= 0:
            raise ValueError("Invalid quantity")

    # Process payment
    payment_result = gateway.charge(order.total)
    return payment_result

After:

def validate_order(order: Order) -> None:
    """Validate order has valid items and total."""
    if not order.items:
        raise ValueError("Empty order")
    if order.total < 0:
        raise ValueError("Invalid total")
    for item in order.items:
        if item.quantity <= 0:
            raise ValueError("Invalid quantity")

def process_order(order: Order) -> PaymentResult:
    validate_order(order)
    return gateway.charge(order.total)

Class Splitting

Split large classes into focused components:

When to split:

  • Class has multiple responsibilities
  • Class has > 500 lines
  • Groups of methods work on different data
  • Testing requires excessive mocking

Splitting strategies:

Extract class:

# Before: God class
class OrderManager:
    def create_order(self): ...
    def validate_order(self): ...
    def calculate_tax(self): ...
    def calculate_shipping(self): ...
    def send_confirmation_email(self): ...
    def send_shipping_notification(self): ...

# After: Focused classes
class OrderService:
    def create_order(self): ...
    def validate_order(self): ...

class PricingService:
    def calculate_tax(self): ...
    def calculate_shipping(self): ...

class NotificationService:
    def send_confirmation_email(self): ...
    def send_shipping_notification(self): ...

Complexity Reduction

Reduce cyclomatic complexity:

Replace conditionals with polymorphism:

# Before: Complex switch
def calculate_price(product_type, base_price):
    if product_type == "physical":
        return base_price + shipping_cost
    elif product_type == "digital":
        return base_price
    elif product_type == "subscription":
        return base_price * 12 * 0.9
    else:
        raise ValueError("Unknown type")

# After: Polymorphism
class Product(ABC):
    @abstractmethod
    def calculate_price(self, base_price): ...

class PhysicalProduct(Product):
    def calculate_price(self, base_price):
        return base_price + self.shipping_cost

class DigitalProduct(Product):
    def calculate_price(self, base_price):
        return base_price

class Subscription(Product):
    def calculate_price(self, base_price):
        return base_price * 12 * 0.9

Extract guard clauses:

# Before: Nested conditionals
def process(data):
    if data:
        if data.is_valid:
            if data.is_ready:
                return do_processing(data)
    return None

# After: Guard clauses
def process(data):
    if not data:
        return None
    if not data.is_valid:
        return None
    if not data.is_ready:
        return None
    return do_processing(data)

Code Migration

Migrate code between patterns or versions:

Migration types:

  • Python 2 to 3
  • Sync to async
  • ORM migrations
  • API version upgrades
  • Framework migrations

Migration workflow:

  1. Assess scope: What needs to change
  2. Create compatibility layer: If gradual migration
  3. Migrate in phases: Start with low-risk areas
  4. Maintain tests: Ensure behavior preserved
  5. Remove old code: Clean up after migration

Example: Sync to Async

# Before: Synchronous
def fetch_user(user_id: int) -> User:
    response = requests.get(f"/users/{user_id}")
    return User.from_dict(response.json())

# After: Asynchronous
async def fetch_user(user_id: int) -> User:
    async with aiohttp.ClientSession() as session:
        async with session.get(f"/users/{user_id}") as response:
            data = await response.json()
            return User.from_dict(data)

Refactoring Workflow

Safe Refactoring Process

  1. Ensure test coverage: Add tests if missing
  2. Run tests: Verify green baseline
  3. Make small change: One refactoring at a time
  4. Run tests again: Verify still green
  5. Commit: Save progress
  6. Repeat: Continue with next change

Pre-Refactoring Checklist

[ ] Tests exist for affected code
[ ] All tests pass
[ ] Change is well understood
[ ] Impact scope identified
[ ] Rollback plan exists

Post-Refactoring Verification

[ ] All tests still pass
[ ] No new linting errors
[ ] Type checking passes
[ ] Functionality unchanged
[ ] Performance acceptable

Common Refactorings

Remove Dead Code

# Find and remove:
# - Unused imports
# - Unused variables
# - Unreachable code
# - Commented-out code
# - Deprecated functions

# Tools:
# - vulture (Python)
# - autoflake (Python)
# - eslint (JavaScript)

Simplify Expressions

# Before
if condition == True:
    return True
else:
    return False

# After
return condition

Introduce Explaining Variables

# Before
if user.age >= 18 and user.country in ['US', 'CA'] and user.verified:
    allow_purchase()

# After
is_adult = user.age >= 18
is_supported_country = user.country in ['US', 'CA']
is_verified = user.verified
can_purchase = is_adult and is_supported_country and is_verified

if can_purchase:
    allow_purchase()

Safety Guidelines

Breaking Changes

When refactoring public APIs:

  1. Add deprecation warnings first
  2. Maintain backwards compatibility
  3. Document migration path
  4. Remove after deprecation period

Database Migrations

When refactoring data models:

  1. Create migration scripts
  2. Test migrations on copy of data
  3. Plan for rollback
  4. Consider zero-downtime migrations

Performance Impact

After refactoring:

  1. Run performance benchmarks
  2. Compare with baseline
  3. Profile if regression found
  4. Optimize if necessary

Integration

Coordinate with other skills:

  • code-quality skill: Measure improvement
  • test-coverage skill: Ensure test coverage
  • architecture-review skill: Validate structural changes
  • git-workflows skill: Proper commit messages for refactors

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.