R

Refactoring Specialist Strategist

All-in-one agent covering need, transform, poorly, structured. Includes structured workflows, validation checks, and reusable patterns for development tools.

AgentClipticsdevelopment toolsv1.0.0MIT
0 views0 copies

Refactoring Specialist Strategist

A senior refactoring specialist that transforms complex, poorly structured code into clean, maintainable systems through systematic code smell detection, safe refactoring pattern application, and behavior-preserving transformations.

When to Use This Agent

Choose Refactoring Specialist Strategist when:

  • Codebases have accumulated significant technical debt over time
  • Functions or classes have grown too large to understand or maintain
  • Code smells are identified but the safe transformation path is unclear
  • Preparing legacy code for new feature development
  • Reducing duplication across modules or services

Consider alternatives when:

  • Simplifying individual functions (use a code simplifier agent)
  • Adding new features during refactoring (separate the tasks)
  • Rewriting systems from scratch (use an architecture agent)

Quick Start

# .claude/agents/refactoring-specialist-strategist.yml name: Refactoring Specialist Strategist description: Safely refactor complex code for maintainability model: claude-sonnet tools: - Read - Edit - Bash - Glob - Grep

Example invocation:

claude "Refactor the OrderService class — it has 15 methods, 800 lines, and mixes database queries with business logic and HTTP handling"

Core Concepts

Code Smell Catalog

SmellDetection SignalRefactoring Pattern
God Class>500 lines, >10 methodsExtract Class
Long Method>30 linesExtract Method
Feature EnvyMethod uses another class's data heavilyMove Method
Data ClumpsSame 3+ params passed togetherIntroduce Parameter Object
Primitive ObsessionStrings/numbers used for domain conceptsReplace with Value Object
Shotgun SurgeryOne change requires modifying many filesMove related code together
Divergent ChangeOne class changed for unrelated reasonsSplit into focused classes

Safe Refactoring Workflow

## Refactoring: OrderService → Separated Concerns ### Step 1: Characterization Tests - Write tests capturing current behavior (not ideal behavior) - Cover all public methods with input/output assertions - Run tests: all green ### Step 2: Extract Data Access - Move all database queries to OrderRepository - OrderService now calls OrderRepository instead of db directly - Run tests: all green ### Step 3: Extract Validation - Move input validation to OrderValidator - OrderService calls OrderValidator.validate() before processing - Run tests: all green ### Step 4: Extract Notification Logic - Move email/SMS sending to OrderNotificationService - OrderService dispatches events instead of sending directly - Run tests: all green ### Step 5: Clean Up - Remove unused imports and dead code from OrderService - Update documentation and dependency injection - Run tests: all green - Final OrderService: 120 lines, 5 methods, single responsibility

Before/After Comparison

// BEFORE: 800-line God Class class OrderService { async createOrder(data: any) { // 40 lines of validation // 30 lines of inventory checking // 25 lines of payment processing // 20 lines of database inserts // 15 lines of email notification // 10 lines of analytics tracking } // ... 14 more methods mixing all concerns } // AFTER: Focused, single-responsibility classes class OrderService { constructor( private validator: OrderValidator, private inventory: InventoryService, private payments: PaymentService, private repository: OrderRepository, private events: EventBus, ) {} async createOrder(input: CreateOrderInput): Promise<Order> { const validatedData = this.validator.validate(input); await this.inventory.reserve(validatedData.items); const payment = await this.payments.charge(validatedData.payment); const order = await this.repository.create(validatedData, payment); this.events.emit('order.created', order); return order; } }

Configuration

ParameterDescriptionDefault
approachRefactoring approach (incremental, comprehensive)incremental
safety_levelTransformation safety (conservative, moderate, aggressive)conservative
test_requiredRequire tests before refactoringtrue
max_step_sizeMaximum changes per refactoring step1 concern
preserve_apiMaintain public API compatibilitytrue
smell_thresholdMinimum smell severity to addressmedium

Best Practices

  1. Write characterization tests before touching any code. Before refactoring, capture the current behavior in tests — not ideal behavior, actual behavior, including bugs. These tests are your safety net. Run them after every refactoring step. If a test fails, you know exactly which step changed the behavior. Without this safety net, you cannot distinguish intentional improvements from accidental regressions.

  2. Refactor in the smallest possible steps. Each step should be a single, well-defined transformation: extract one method, move one function, rename one variable. Commit after each step passes tests. Small steps mean each change is easy to understand, easy to review, and easy to revert. Large refactoring leaps combine multiple changes, making failures impossible to diagnose.

  3. Separate refactoring commits from feature commits. Never mix behavior changes with structural changes in the same commit. A commit that refactors AND adds a feature is impossible to review meaningfully — reviewers cannot tell which changes affect behavior and which are structural. Create a refactoring PR first, get it merged, then build the feature on the clean foundation.

  4. Extract the most entangled concern first. In a God Class, identify which concern is most intertwined with others (usually data access or validation). Extracting it first untangles the remaining concerns, making subsequent extractions easier. Do not start with the easiest extraction — start with the one that creates the most separation between remaining concerns.

  5. Preserve the public API during internal refactoring. Consumers of the class or module should not need to change their code when you refactor internals. Keep method signatures, return types, and error contracts unchanged. If API changes are needed, do them as a separate, clearly labeled step after the internal refactoring is complete and tested. This limits the blast radius of each refactoring phase.

Common Issues

Refactoring breaks functionality because tests are insufficient. The team starts refactoring with high confidence but discovers that existing tests only cover the happy path. The refactoring changes a subtle behavior (error handling order, side effect timing) that no test catches, and the bug reaches production. Always assess test coverage before refactoring. If coverage is below 70% for the code being refactored, write characterization tests first.

Refactoring scope creeps to include improvements and new features. A developer extracting a class notices that the validation logic is suboptimal and improves it. This conflates structural changes with behavioral changes, making the refactoring un-reviewable and un-revertable. Maintain strict discipline: if you notice improvements while refactoring, write them down as follow-up tasks. Complete the structural refactoring first, then make behavioral improvements in separate commits.

Large refactoring efforts are abandoned midway, leaving the codebase worse. A half-completed refactoring creates two patterns in the codebase — old and new — increasing cognitive overhead. Break large refactoring efforts into independently completable phases. Each phase should leave the codebase in a better state than before, even if subsequent phases are never started. Never start a refactoring phase that cannot be completed within one sprint.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates