home / skills / amnadtaowsoam / cerebraskills / refactoring-strategies
This skill helps you apply safe refactoring patterns like Strangler Fig and Parallel Change to modernize Python code without breaking production.
npx playbooks add skill amnadtaowsoam/cerebraskills --skill refactoring-strategiesReview the files below or copy the command above to add this skill to your agents.
---
name: Safe Refactoring Patterns
description: Expert-level framework for identifying, planning, and executing safe refactoring without breaking production systems, including Strangler Fig and Parallel Change patterns.
---
# Safe Refactoring Patterns
## Overview
Safe refactoring is the practice of modifying existing code without breaking functionality. This skill teaches patterns and protocols for making changes to production codebases safely, focusing on "brownfield" development where existing systems must remain operational while improvements are made.
## Why This Matters
- **Reduces Risk**: Safe refactoring patterns minimize the risk of breaking production when modifying existing code
- **Increases System Stability**: Following proper protocols ensures systems remain stable during and after refactoring
- **Reduces Technical Debt**: Systematic refactoring prevents debt accumulation in the short term
- **Improves Development Velocity**: Cleaner, well-structured code is faster to develop and maintain
- **Reduces Debugging Time**: Better code quality means fewer bugs and easier troubleshooting
- **Enables Collaboration**: Consistent patterns make team collaboration smoother
- **Increases Development Transparency**: Clear processes and documentation improve visibility into changes
---
## Core Concepts
### 1. Refactoring Safety Principles
Foundational principles for safe code modification:
- **Never Break What Works**: Existing functionality must remain intact
- **Change in Small Steps**: Each change should be independently verifiable
- **Verify After Each Step**: Run tests and checks before proceeding
- **Maintain Backward Compatibility**: Don't break existing consumers
- **Have a Rollback Plan**: Know how to revert if something goes wrong
- **Document Changes**: Explain why and what was changed
### 2. The Strangler Fig Pattern
Gradual replacement strategy for legacy systems:
- **Create New Implementation**: Build new functionality alongside old code
- **Add Facade/Routing Layer**: Route traffic between old and new implementations
- **Migrate Traffic Gradually**: Incrementally switch users to new system
- **Monitor and Verify**: Ensure new system behaves correctly
- **Remove Old System**: Complete removal once migration is verified
### 3. The Parallel Change Pattern
Three-phase approach for API and data structure changes:
- **Phase 1: Expand**: Add new functionality while keeping old working
- **Phase 2: Migrate**: Gradually switch consumers to new implementation
- **Phase 3: Contract**: Remove old functionality once migration is complete
### 4. Verification Between Changes
Systematic testing and validation protocols:
- **Unit Verification**: Test individual components after changes
- **Integration Verification**: Test component interactions
- **Regression Verification**: Ensure old functionality still works
- **Performance Verification**: Confirm no performance degradation
### 5. Refactoring Checklists
Comprehensive lists for before, during, and after refactoring:
- **Before Starting**: Understand code, write tests, create plan
- **During Refactoring**: Small steps, verify each step, commit frequently
- **After Refactoring**: Verify all tests, update documentation, cleanup
### 6. Common Refactoring Scenarios
Frequently encountered refactoring situations:
- **Extracting a Function**: Break down complex functions
- **Renaming a Method**: Use Parallel Change pattern
- **Changing Data Structure**: Use Strangler Fig pattern
## Quick Start
1. **Identify Refactoring Need**: Determine what code needs improvement and why
2. **Understand Current Behavior**: Analyze existing code, dependencies, and edge cases
3. **Write Tests for Current Behavior**: Create comprehensive tests before making changes
4. **Plan Refactoring Steps**: Break down refactoring into small, verifiable steps
5. **Execute Steps One by One**: Implement each step, verify after each one
6. **Verify After Each Step**: Run all tests and checks before proceeding
7. **Complete Refactoring**: Finish all planned changes and final verification
```typescript
// Example: Extracting a function safely
// BEFORE: Complex function
function processOrder(order: Order) {
const taxRate = order.state === 'CA' ? 0.08 : 0.05;
const tax = order.subtotal * taxRate;
let discount = 0;
if (order.couponCode) {
discount = order.subtotal * 0.1;
}
const total = order.subtotal + tax - discount;
return { subtotal: order.subtotal, tax, discount, total };
}
// STEP 1: Extract tax calculation (verify still works)
function calculateTax(subtotal: number, state: string): number {
const taxRate = state === 'CA' ? 0.08 : 0.05;
return subtotal * taxRate;
}
function processOrder(order: Order) {
const tax = calculateTax(order.subtotal, order.state);
// ... rest of code
}
// STEP 2: Extract discount calculation (verify still works)
function calculateDiscount(subtotal: number, couponCode?: string): number {
if (!couponCode) return 0;
return subtotal * 0.1;
}
function processOrder(order: Order) {
const tax = calculateTax(order.subtotal, order.state);
const discount = calculateDiscount(order.subtotal, order.couponCode);
// ... rest of code
}
```
## Production Checklist
- [ ] Pre-refactoring tests written and passing
- [ ] Current behavior fully understood
- [ ] All dependencies identified
- [ ] Refactoring plan documented
- [ ] Rollback plan prepared
- [ ] Branch/backup created
- [ ] Each change verified independently
- [ ] Tests run after each step
- [ ] Backward compatibility maintained
- [ ] Performance validated
- [ ] Documentation updated
- [ ] Code reviewed before merge
- [ ] Staging deployment verified
- [ ] Monitoring configured
- [ ] Team notified of changes
## Anti-patterns
1. **Skipping Verification**: Not testing after each change leads to cumulative failures
2. **Making Too Many Changes at Once**: Large, batched changes are hard to debug and rollback
3. **Not Having Tests**: Refactoring without tests risks breaking existing functionality
4. **Breaking Backward Compatibility**: Breaking existing APIs causes integration failures
5. **No Rollback Plan**: Without a rollback plan, failures can't be quickly reversed
6. **Refactoring Without Understanding**: Changing code without understanding it causes subtle bugs
7. **Forgetting to Update Documentation**: Outdated docs confuse future developers
8. **Premature Optimization**: Focus on correctness and clarity before performance
## Integration Points
- **Testing Frameworks**: Jest, Pytest, JUnit, NUnit for comprehensive test coverage
- **Code Analysis Tools**: SonarQube, CodeQL, Coverity for automated quality checks
- **CI/CD Platforms**: GitHub Actions, GitLab CI, Azure Pipelines for automated verification
- **Monitoring Tools**: Datadog, New Relic, Prometheus, Grafana for tracking changes
- **Version Control**: Git, GitHub, GitLab, Bitbucket for branch management
- **Documentation Platforms**: Confluence, Notion, GitHub Wiki for change documentation
- [`code-review`](../../01-foundations/code-review/SKILL.md) for reviewing refactored code
- [`technical-debt-management`](../../00-meta-skills/technical-debt-management/SKILL.md) for tracking refactoring initiatives
## Further Reading
- [Refactoring Guru](https://refactoring.guru/) - Comprehensive refactoring patterns catalog
- [Working Effectively with Legacy Code by Michael Feathers](https://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131170842) - Strategies for handling legacy codebases
- [Refactoring by Martin Fowler](https://www.amazon.com/Refactoring-Improving-Existing-Code/dp/0201485672) - Refactoring techniques and principles
- [Clean Code by Robert C. Martin](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350872) - Writing maintainable code
- [The Pragmatic Programmer](https://www.amazon.com/Pragmatic-Programmer-Journey-Mastery/dp/0135957052) - General programming best practices
This skill presents an expert-level framework for identifying, planning, and executing safe refactoring in production codebases. It focuses on brownfield development and provides patterns like Strangler Fig and Parallel Change to reduce risk while improving design. The guidance emphasizes small, verifiable steps, verification between changes, and clear rollback and monitoring practices.
The skill inspects typical refactoring workflows and prescribes concrete patterns: build-new-alongside-old (Strangler Fig) and expand-migrate-contract (Parallel Change). It layers verification steps—unit, integration, regression, and performance checks—after each incremental change. It also provides checklists for before, during, and after refactoring, and maps integrations with CI, testing, and monitoring tools to ensure safe deployments.
How do I decide between Strangler Fig and Parallel Change?
Use Strangler Fig when replacing an entire subsystem or service; use Parallel Change for API or data-structure evolution where old and new variants must coexist during migration.
What verification steps are essential after each change?
At minimum run unit tests, integration tests for affected interactions, regression tests for core flows, and quick performance smoke tests; add monitoring to observe production behavior during gradual rollouts.