Automate It
Create scripts to automate common refactoring patterns
You’ve inherited a 5-year-old e-commerce backend written in Node.js with Express. It has no tests, uses callbacks instead of promises, mixes business logic with database queries, and has grown to 15,000 lines across 50+ files. Your task: modernize it without breaking existing functionality that serves 10,000 daily users.
By completing this lesson, you’ll master:
Transform a legacy codebase by:
Open the legacy project in Cursor and start with Ask mode:
@src"Analyze this codebase and provide:1. Technology stack and versions2. Overall architecture pattern3. Main entry points and critical paths4. Code quality assessment5. Potential risks and technical debt"
@package.json @package-lock.json"Analyze dependencies:- Which are outdated and need updates?- Which are deprecated or abandoned?- Which have known security vulnerabilities?- What's the upgrade path for critical dependencies?"
Switch to Agent mode:
@src"Create comprehensive architecture documentation:- System overview diagram (mermaid)- Component relationships- Data flow diagrams- API endpoint mapping- Database schema documentationSave to docs/architecture/legacy-analysis.md"
@src/routes @src/controllers"Trace the complete flow for:1. User registration and login2. Product search and display3. Order placement4. Payment processingDocument each flow with sequence diagrams"
@src"Identify and document all business rules:- Pricing calculations- Discount logic- Inventory management- User permission rules- Payment validationCreate a business rules document"
@src/models @src/db"Analyze database interactions:- List all tables/collections used- Identify relationships- Find N+1 queries- Document transaction boundaries- Note missing indexes"
"Set up modern testing framework:- Install Jest and Supertest- Configure for existing code- Add test database setup- Create test utilities- Add npm scripts for testing"
@src/routes/products.js"Generate integration tests for product endpoints:- Test all CRUD operations- Include edge cases- Test error scenarios- Validate response formats- Check authentication/authorization"
@src/services @src/utils"Generate unit tests for business logic:- Price calculation functions- Discount application- Inventory checks- Data validation- Utility functionsAim for 80% coverage of critical paths"
@docs/architecture/legacy-analysis.md"Create a detailed modernization plan:- Priority order for refactoring- Risk assessment for each module- Backward compatibility requirements- Performance improvement opportunities- Timeline with milestones"
@src/controllers/products.js"Refactor this controller:- Convert callbacks to async/await- Add proper error handling- Maintain exact same behavior- Keep API compatibilityShow before/after comparison"
Example transformation:
// Beforefunction getProduct(req, res) { db.query('SELECT * FROM products WHERE id = ?', [req.params.id], function(err, results) { if (err) { res.status(500).send('Error'); return; } if (results.length === 0) { res.status(404).send('Not found'); return; } res.json(results[0]); });}
// Afterasync function getProduct(req, res) { try { const [product] = await db.query( 'SELECT * FROM products WHERE id = ?', [req.params.id] );
if (!product) { return res.status(404).json({ error: 'Product not found' }); }
res.json(product); } catch (error) { logger.error('Error fetching product:', error); res.status(500).json({ error: 'Internal server error' }); }}
@src/controllers @src/services"Extract business logic into service layer:- Create service classes/modules- Move business rules from controllers- Add dependency injection- Improve testability- Maintain controller interfaces"
"Migrate from raw SQL to query builder:- Install and configure Knex.js- Create migration from existing schema- Convert queries incrementally- Add connection pooling- Implement transactions properly"
@src/models"Optimize database queries:- Fix N+1 query problems- Add appropriate indexes- Implement caching layer- Batch similar queries- Add query logging/monitoring"
"Implement data validation:- Install Joi or Zod- Create schemas for all inputs- Add validation middleware- Improve error messages- Document validation rules"
Always follow this pattern:
// 1. Understand current behavior@old-file.js"Explain what this code does and all edge cases"
// 2. Add tests for current behavior"Generate tests that verify current behavior"
// 3. Refactor with confidence"Refactor this code while maintaining all tested behavior"
// 4. Verify tests still pass"Run tests and fix any failures"
Migrate module by module:
// Create new version alongside old@src/controllers/products-old.js"Create modernized version at products-new.js"
// Add feature flag"Add feature flag to switch between old and new implementation"
// Test in production// Gradually migrate traffic// Remove old version when stable
Generate and maintain documentation:
@src/routes"Generate OpenAPI/Swagger documentation from existing routes"
@src/models"Generate database documentation with relationships"
@src/services"Generate JSDoc comments explaining business logic"
Problem: Refactoring breaks existing functionality
Solution:
Problem: Trying to fix everything at once
Solution:
Problem: Not understanding why code was written a certain way
Solution:
Take your refactoring further:
Performance Optimization
Microservices Migration
Modern Infrastructure
Track these metrics:
Teams using these techniques report:
Before starting any refactoring:
ROI: 10x return within 6 months through reduced bugs and faster development
You’ve mastered legacy code transformation. Ready for more challenges?
Automate It
Create scripts to automate common refactoring patterns
Scale It
Apply techniques to larger, more complex systems
Teach It
Share your refactoring patterns with your team
Continue to Bug Hunting Workflow →