Code Refactoring Guide
Refactoring types, signs, steps, and principles.
Refactoring Types
Extract Method
Break into smaller methods
When: Long methods, duplicate code
Extract Class
Move to new class
When: Too many responsibilities
Rename
Better names
When: Unclear purpose
Replace Magic Number
Named constants
When: Hardcoded values
Decompose Conditional
Break complex if
When: Nested conditions
Introduce Parameter
Pass instead of global
When: Dependencies unclear
Signs to Refactor
⚠️ Long methods (over 20 lines)
⚠️ Duplicate code blocks
⚠️ Large classes (too many methods)
⚠️ Unclear names
⚠️ Deep nesting
⚠️ Too many parameters
⚠️ Magic numbers/strings
⚠️ Dead code
Refactoring Steps
1. Identify problem code
2. Understand current behavior
3. Write tests if missing
4. Make small changes
5. Run tests after each change
6. Commit frequently
7. Document changes
8. Review with team
Key Principles
Small incremental changes
Tests before refactoring
Don't change behavior
One refactoring at a time
Commit after each step
Code review changes
Document intent
Know when to stop
Refactoring Checklist
1. Have tests covering current behavior. 2. Identify specific problem to address. 3. Plan refactoring approach. 4. Make smallest possible change. 5. Run tests immediately. 6. Continue if tests pass. 7. Commit after each successful change. 8. Review changes with team. 9. Document reasoning in commit. 10. Know when refactoring complete. Refactoring = improve structure without changing behavior. Tests are prerequisite. Small steps, test frequently. Don't refactor without tests. Don't change behavior during refactoring."