Refactoring

From 5throck/ai-workspace-standards · View interactive version

Refactoring is an AI agent skill from the GitHub repository 5throck/ai-workspace-standards. Improves code structure and design while preserving behavior using systematic refactoring techniques. Use when: cleaning up code, reducing duplication, improving maintainability, or paying down technical debt.

How to use this skill

Skill file

Context

This skill provides systematic refactoring capabilities, transforming code into better designs while ensuring behavior remains unchanged. It emphasizes safety, test coverage, and incremental improvements.

When to Use

Code Cleanup:

Debt Reduction:

Design Improvement:

Maintainability:


Execution Steps

Step 1: Refactoring Preparation

Purpose: Ensure safe refactoring environment.

Preparation Checklist:

  1. Test Coverage:
  1. Baseline Understanding:
  1. Safety Measures:

Refactoring Goals:


Step 2: Identify Code Smells

Purpose: Find specific refactoring opportunities.

Common Code Smells:

  1. Duplication:
  1. Long Methods:
  1. Large Classes:
  1. Poor Names:
  1. Complex Conditionals:

Detection Techniques:

Prioritization:


Step 3: Apply Refactorings Systematically

Purpose: Transform code using proven techniques.

Refactoring Process:

  1. Select Small Refactoring:
  1. Apply Refactoring:
  1. Run Tests:
  1. Commit Incremental Change:

Common Refactoring Patterns:

Extract Method:

# Before
def process_order(order):
    # validate
    if not order.customer_id:
        raise ValueError("No customer")
    if not order.items:
        raise ValueError("No items")
    # calculate
    total = sum(item.price for item in order.items)
    tax = total * 0.1
    final = total + tax
    # save
    order.total = final
    order.save()

# After
def process_order(order):
    validate_order(order)
    final = calculate_order_total(order)
    save_order(order, final)

def validate_order(order):
    if not order.customer_id:
        raise ValueError("No customer")
    if not order.items:
        raise ValueError("No items")

def calculate_order_total(order):
    total = sum(item.price for item in order.items)
    tax = total * 0.1
    return total + tax

def save_order(order, total):
    order.total = total
    order.save()

Rename Variable/Method:

# Before
def d(x, y):
    return x * y * 24

# After
def calculate_daily_hours(hours_per_day, days_worked):
    return hours_per_day * days_worked * 24

Replace Magic Numbers:

# Before
if score > 75:
    grade = "A"

# After
EXCELLENCE_THRESHOLD = 75
if score > EXCELLENCE_THRESHOLD:
    grade = "A"

Decompose Conditional:

# Before
def calculate_shipping(order):
    if order.customer.is_premium and order.total > 100 and order.has_free_shipping:
        return 0
    elif order.customer.is_premium and order.total > 50:
        return 5
    else:
        return 10

# After
def calculate_shipping(order):
    if qualifies_for_free_shipping(order):
        return 0
    if qualifies_for_reduced_shipping(order):
        return 5
    return 10

def qualifies_for_free_shipping(order):
    return (order.customer.is_premium and 
            order.total > 100 and 
            order.has_free_shipping)

def qualifies_for_reduced_shipping(order):
    return order.customer.is_premium and order.total > 50

Step 4: Maintain Test Safety Net

Purpose: Ensure refactoring doesn't break behavior.

Test Strategy:

  1. Before Refactoring:
  1. During Refactoring:
  1. After Refactoring:

Regression Prevention:

Test Safety Indicators:

✅ Safe to refactor:

❌ Risky to refactor:


Step 5: Incremental Improvement

Purpose: Make steady progress without big risks.

Incremental Approach:

  1. Small Steps:
  1. Build Confidence:
  1. Track Progress:

Incremental Refactoring Cycle:

Identify Issue → Plan Refactoring → Apply Change → Run Tests → Commit → Repeat

Batching Refactorings:


Step 6: Validate Improvements

Purpose: Confirm refactoring achieved goals.

Validation Checklist:

  1. Behavior Preservation:
  1. Code Quality:
  1. Maintainability:
  1. Performance:

Quality Metrics:


Output Format

For Code Cleanup:

For Debt Reduction:

For Design Improvement:


Best Practices

Refactoring Discipline:

✅ Do:

❌ Don't:

Safety First:

✅ Do:

❌ Don't:


Common Mistakes to Avoid

Refactoring Anti-Patterns:

  1. Refactoring Without Tests: Making changes without safety net
  2. Big Bang Refactoring: Trying to fix everything at once
  3. Mixed Changes: Combining refactoring with feature work
  4. Premature Optimization: Optimizing before measuring
  5. Over-Engineering: Adding complexity for hypothetical future needs

Process Anti-Patterns:

  1. Ignoring Failing Tests: Continuing despite test failures
  2. Skipping Validation: Not confirming behavior preserved
  3. No Clear Goal: Refactoring without specific improvement target
  4. Analysis Paralysis: Spending too much time planning
  5. Refactoring Procrastination: Putting off necessary improvements

Spoke Derivation Note

This file is the hub-doctrine canonical for the co-develop generic dev spine

(spec 2026-11-01-hub-consolidation-design, Phase 1 batch D). Co-develop

pipelines run it as written. A spoke variant derives from this doctrine by

substituting the bindings below — the derivation never edits the

single-valued frontmatter doctrine: scope: co-develop stays as written

here, and the spoke label lives in this note only.

No {{PROJECT_*}} placeholder is needed in this skill: its per-spoke deltas

are frontmatter labels, not body prose, so they are documented as bindings

rather than parameterized. This canonical also cleans the stray ", EOF

artifact inherited from the pre-consolidation copies (all four measured

L2/L3 copies carried it).

| Spoke | Derivation binding |

|---|---|

| co-game | Ships byte-identical to co-develop, including scope: co-develop (merge ruling 2026-11-06, DEC-20261106-03: diverged same-version copies are merged, not split by version bump); no per-spoke scope rendering. |

| co-learning | Not adopted — absent from Projects/co-learning and its template. The fleet skill-graph projection carries only a dangling reference node for it (content_hash null); it is not an installed consumer. |

| co-abap | Not adopted — co-abap carries no refactoring capability; its abap-dev skill is a domain-specific asset outside this generic spine. |


Related Skills


Refactoring Tools

Automated Refactoring:

Code Analysis Tools:

Duplicate Code Detection:


Refactoring Patterns Reference

Organizing Data:

Simplifying Conditional Expressions:

Simplifying Method Calls:

Dealing with Generalization:


When NOT to Refactor

Avoid Refactoring When:

Alternatives:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.