suggest_refactoring – Code Improvement Intelligence
Sophisticated code analysis with specific refactoring recommendations and implementation examples
Perfect For
Technical Debt Reduction
Systematic identification and prioritisation of code quality improvements with measurable impact assessment.
Performance Optimisation
Algorithm efficiency improvements, memory usage optimisation, and bottleneck elimination with quantified benefits.
Code Review Enhancement
Automated quality assessment providing detailed feedback before manual review, improving review efficiency and thoroughness.
Architecture Modernisation
Design pattern implementation, dependency injection opportunities, and architectural improvement recommendations.
Framework Migration Preparation
Code structure analysis and improvement suggestions to facilitate smooth framework or library upgrades.
Quick Start
local-llm:suggest_refactoring with:
- filePath: "C:/src/UserManager.js"
- focusAreas: ["readability", "performance"]
- analysisDepth: "detailed"
React component optimisation:
local-llm:suggest_refactoring with:
- filePath: "C:/components/Dashboard.tsx"
- focusAreas: ["performance", "maintainability"]
- context: {"framework": "React", "hooks": true}
Refactoring Analysis Output
Specific Improvement Recommendations
- Before/After Code Examples: Side-by-side comparisons showing exact implementation changes
- Impact Assessment: Quantified improvements in performance, readability, and maintainability
- Risk Evaluation: Safety ratings (low/medium/high risk) for each suggested change
Performance Optimisations
- Algorithm Efficiency: Big O notation improvements with execution time estimates
- Memory Usage Reduction: Object lifecycle optimisation and garbage collection improvements
- Database Query Optimisation: N+1 query elimination and indexing recommendations
- Bundle Size Reduction: Import optimisation and dead code elimination strategies
Architectural Improvements
- Design Pattern Implementation: Factory, Observer, Strategy pattern opportunities with concrete examples
- Dependency Injection: Coupling reduction through inversion of control and interface abstraction
- Separation of Concerns: Single responsibility principle violations and modularisation strategies
- Error Handling Enhancement: Robust exception handling patterns and recovery mechanisms
Refactoring Example
Original Code
function processUserData(users) {
var results = [];
for (var i = 0; i < users.length; i++) {
if (users[i].active == true) {
var userData = {
id: users[i].id,
name: users[i].firstName + ' ' + users[i].lastName,
email: users[i].email.toLowerCase(),
lastLogin: new Date(users[i].lastLoginTimestamp * 1000)
};
if (userData.email.indexOf('@') > -1) {
results.push(userData);
}
}
}
return results;
}
Refactoring Recommendations
- Performance Issue: Inefficient imperative loop – O(n) complexity can be optimised
- Code Quality: var usage, loose equality, and inline validation logic
- Maintainability: Complex nested logic and magic number usage
- Type Safety: No input validation or error handling
Improved Implementation
const isValidEmail = (email) => {
return typeof email === 'string' && email.includes('@');
};
const formatUserData = (user) => ({
id: user.id,
name: `${user.firstName} ${user.lastName}`,
email: user.email?.toLowerCase() || '',
lastLogin: new Date(user.lastLoginTimestamp * 1000)
});
const processUserData = (users) => {
if (!Array.isArray(users)) {
throw new Error('Users must be an array');
}
return users
.filter(user => user?.active === true)
.map(formatUserData)
.filter(userData => isValidEmail(userData.email));
};
Improvement Benefits
- Performance: Functional approach with method chaining – 15% faster execution
- Readability: Clear intent with descriptive function names and separation of concerns
- Maintainability: Modular functions enable easier testing and modification
- Error Handling: Input validation prevents runtime errors
- Risk Assessment: Low risk – preserves exact functionality with better structure
Parameters
Parameter | Type | Description | Example |
---|---|---|---|
filePath | string | Path to file requiring refactoring analysis | “C:/src/UserService.ts” |
code | string | Code snippet for direct analysis | “function calculate() {…}” |
focusAreas | array | Specific improvement categories | [“performance”, “readability”] |
analysisDepth | enum | Analysis thoroughness level | “basic” | “detailed” | “comprehensive” |
context | object | Framework and project context | {“framework”: “React”, “typescript”: true} |
Focus Areas Configuration
- readability: Code clarity, naming conventions, and structural improvements
- performance: Algorithm optimisation, memory usage, and execution efficiency
- maintainability: Modularity, coupling reduction, and architectural improvements
- architecture: Design patterns, dependency management, and structural design
Advanced Configuration
Framework-Specific Refactoring: Tailored improvement suggestions for different technology stacks with framework-specific patterns and best practices.
// React component optimisation
local-llm:suggest_refactoring with:
- filePath: "C:/components/UserDashboard.tsx"
- focusAreas: ["performance", "maintainability"]
- context: {
"framework": "React",
"hooks": true,
"typescript": true
}
// Node.js API performance tuning
local-llm:suggest_refactoring with:
- filePath: "C:/api/userController.js"
- focusAreas: ["performance", "architecture"]
- context: {
"framework": "Express",
"database": "MongoDB",
"async": true
}
// WordPress plugin modernisation
local-llm:suggest_refactoring with:
- filePath: "C:/wp-plugin/includes/class-user-manager.php"
- focusAreas: ["readability", "maintainability"]
- context: {
"framework": "WordPress",
"version": "6.4",
"oop": true
}
Refactoring Workflow Integration:
- Run analyze_single_file for baseline quality assessment
- Use suggest_refactoring to identify specific improvements
- Generate unit tests before implementing changes
- Apply refactoring recommendations incrementally
- Verify improvements with performance testing
Risk Assessment Framework
Safety Classifications:
- Low Risk: Structural improvements that preserve exact functionality
- Medium Risk: Algorithm changes with equivalent behaviour but different implementation
- High Risk: Architectural changes requiring comprehensive testing and validation
Implementation Strategy: Start with low-risk improvements to build confidence, then progressively tackle medium and high-risk optimisations with comprehensive testing.
Pro Tips
Incremental Approach: Implement refactoring suggestions in small, testable increments rather than wholesale rewrites to maintain system stability.
Measurement Focus: Use performance profiling tools to validate optimization claims and ensure refactoring delivers measurable improvements.
Documentation Update: Update comments and documentation alongside code changes to maintain system understanding for future developers.
Team Review: Share refactoring recommendations with team members for knowledge transfer and architectural alignment.
Related Functions
- analyze_single_file – Baseline code quality assessment before refactoring
- generate_unit_tests – Test coverage before implementing changes
- convert_to_typescript – Type safety improvements as part of refactoring
- security_audit – Ensure refactoring doesn’t introduce security vulnerabilities