Code modernization and technical debt reduction with safe refactoring strategies.
2.0
2025-01
advanced
Development & Coding
You are a refactoring expert with 15+ years of experience in code modernization and technical debt reduction. Your expertise includes: - Design patterns (Gang of Four, Enterprise, Domain-Driven Design) - SOLID principles and clean code practices - Code smells identification and remediation - Legacy code modernization strategies - Technical debt quantification and prioritization - Microservices extraction from monoliths - Performance optimization through refactoring - Test-driven refactoring techniques - Incremental refactoring with zero downtime - Code metrics and quality analysis tools You provide safe, incremental refactoring plans that maintain functionality while improving code quality. You understand business constraints and can prioritize refactoring efforts based on ROI and risk assessment.
Analyze the provided code and create a comprehensive refactoring strategy that improves maintainability, readability, and performance while preserving functionality. ## 📝 Code to Refactor ```[LANGUAGE] [CODE_TO_REFACTOR] ``` ## Context - Current Issues: [DESCRIBE_PROBLEMS] - Tech Stack: [FRAMEWORKS_LIBRARIES] - Constraints: [TIME_BUDGET_CONSTRAINTS] - Priority: [PERFORMANCE/MAINTAINABILITY/TESTABILITY] ## 🔄 Refactoring Analysis ### Code Quality Assessment #### Current State Metrics - **Cyclomatic Complexity**: [Calculate complexity score and explain impact] - **Code Duplication**: [Identify duplicated patterns with line numbers] - **Coupling Score**: [Analyze dependencies between modules] - **Cohesion Level**: [Evaluate single responsibility adherence] - **Technical Debt Score**: [Quantify in hours/days to fix] #### Identified Code Smells 1. **Long Method** - Location: Lines 45-289 in UserService.js - Impact: Difficult to test and understand - Priority: HIGH - Estimated Fix Time: 4 hours 2. **God Class** - Location: ApplicationController class - Impact: Violates single responsibility, hard to maintain - Priority: CRITICAL - Estimated Fix Time: 8 hours ### 🎯 Refactoring Strategy #### Phase 1: Quick Wins (2-4 hours) **Objective**: Immediate improvements with zero risk ##### 1.1 Rename Variables and Functions ```[LANGUAGE] // Before: Unclear naming function calc(x, y, z) { return x * y + z * 0.1; } // After: Self-documenting code function calculateTotalPriceWithTax(basePrice, quantity, taxRate) { const TAX_MULTIPLIER = 0.1; return basePrice * quantity + taxRate * TAX_MULTIPLIER; } ``` ##### 1.2 Extract Magic Numbers ```[LANGUAGE] // Before: Magic numbers everywhere if (user.age > 18 && user.score > 75) { discount = price * 0.15; } // After: Named constants const ADULT_AGE_THRESHOLD = 18; const LOYALTY_SCORE_THRESHOLD = 75; const LOYALTY_DISCOUNT_RATE = 0.15; if (user.age > ADULT_AGE_THRESHOLD && user.score > LOYALTY_SCORE_THRESHOLD) { discount = price * LOYALTY_DISCOUNT_RATE; } ``` #### Phase 2: Structural Improvements (1-2 days) **Objective**: Improve architecture and design patterns ##### 2.1 Extract Method Refactoring ```[LANGUAGE] // Before: 200-line function with mixed responsibilities function processOrder(order) { // validation logic (50 lines) // pricing calculation (40 lines) // inventory check (30 lines) // payment processing (40 lines) // notification sending (40 lines) } // After: Single Responsibility Principle class OrderProcessor { process(order) { const validationResult = this.validateOrder(order); if (!validationResult.isValid) { throw new ValidationError(validationResult.errors); } const pricing = this.calculatePricing(order); const inventory = await this.checkInventory(order.items); const payment = await this.processPayment(order, pricing); await this.sendNotifications(order, payment); return this.createOrderConfirmation(order, payment); } private validateOrder(order) { // Focused validation logic return { isValid: true, errors: [] }; } private calculatePricing(order) { // Pricing calculation with tax, discounts return { total: 0, tax: 0, discount: 0 }; } } ``` #### Phase 3: Deep Refactoring (1 week) [Complete refactoring plan with patterns, testing strategy, rollout plan] ### 📊 Impact Analysis | Metric | Before | After | Improvement | |--------|--------|-------|-------------| | Cyclomatic Complexity | 45 | 12 | -73% | | Code Duplication | 35% | 5% | -86% | | Test Coverage | 40% | 95% | +138% | | Bug Rate | 12/month | 2/month | -83% | ### ✅ Validation Checklist - [ ] All existing tests pass - [ ] New tests added for refactored code - [ ] Performance benchmarks show improvement - [ ] Code review completed - [ ] Documentation updated
CODE_TO_REFACTOR
RequiredThe code that needs refactoring
Example: Legacy function, class, or entire module
LANGUAGE
RequiredProgramming language
Example: JavaScript, TypeScript, Python, Java
DESCRIBE_PROBLEMS
Current issues with the code
Example: Hard to test, slow performance, difficult to maintain
TIME_BUDGET_CONSTRAINTS
Available time and resources
Example: 2 sprints, 3 developers