Coding & Engineering

Code Refactoring Expert

Transforms legacy or poorly structured code into clean, maintainable implementations while preserving functionality and minimizing risk. Provides systematic refactoring strategies with comprehensive safety nets, validation criteria, and incremental execution plans.

Prompt

---

## Example Usage

### Input

We have a 15-year-old Java monolith with 500K LOC. Lots of duplicated code, methods with 600+ lines, tightly coupled components. Current test coverage is 30%. We need to add a new payment integration but the current PaymentProcessor code is too rigid to extend safely.

### Output

**Complexity Analysis**

Hotspots identified using cyclomatic complexity and change frequency:

| File                    | Lines | Complexity | Coupling | Priority |
| ----------------------- | ----- | ---------- | -------- | -------- |
| `PaymentProcessor.java` | 847   | 45         | High     | Critical |
| `OrderService.java`     | 1,200 | 38         | High     | High     |
| `CustomerManager.java`  | 600   | 22         | Medium   | Medium   |

Code duplication analysis: 23% overall duplication, concentrated in validation logic and error handling patterns.

Root causes:

- No interface abstractions for payment types (violates Open-Closed Principle)
- Database access mixed with business logic (violates Single Responsibility)
- Copy-paste validation instead of shared utilities

**Prioritized Refactoring Targets**

| Priority | Target           | Pattern                      | Risk   | Pre-requisite Coverage  |
| -------- | ---------------- | ---------------------------- | ------ | ----------------------- |
| 1        | PaymentProcessor | Extract Interface + Strategy | High   | 80% before refactor     |
| 2        | OrderService     | Extract Class + Facade       | Medium | 70% before refactor     |
| 3        | Validation logic | Extract Method + Template    | Low    | Existing 30% sufficient |

**Phase 1: Safety Net (Weeks 1-3)**

Goal: Establish test coverage as safety net before any code changes

1. **Characterization Tests for PaymentProcessor**
   - Test current behavior, not expected behavior
   - Cover all code paths including error cases
   - Use golden master testing for complex outputs
   - Target: 80% line coverage, 70% branch coverage

2. **Integration Test Suite for Payment Flows**
   - End-to-end tests covering credit, debit, refund flows
   - Mock external payment gateway responses
   - Test timeout and error recovery scenarios