Refactoring Techniques
66 classic refactoring techniques organized into 6 categories.
Quick Reference
| Category | Count | When to Use |
|---|---|---|
| Composing Methods | 9 | Methods too long, complex expressions, tangled local variables |
| Moving Features | 8 | Features in wrong class, class does too much/little |
| Organizing Data | 16 | Data fields need encapsulation, type codes, magic numbers |
| Simplifying Conditionals | 8 | Complex conditionals, nested if/else, null checks |
| Simplifying Method Calls | 14 | Awkward method signatures, unclear naming, side effects |
| Dealing with Generalization | 12 | Inheritance hierarchy issues, duplicate code across subclasses |
Technique Selection Guide
For Long/Complex Methods
- •Extract Method - Group related code into named method
- •Extract Variable - Break complex expressions into named parts
- •Replace Temp with Query - Convert temp variables to methods
- •Replace Method with Method Object - When local vars prevent extraction
For Misplaced Features
- •Move Method/Field - Feature used more in another class
- •Extract Class - Class has multiple responsibilities
- •Inline Class - Class does almost nothing
For Data Organization
- •Encapsulate Field/Collection - Public fields need protection
- •Replace Magic Number with Constant - Unclear numeric literals
- •Replace Type Code with Subclasses/State-Strategy - Type codes controlling behavior
For Complex Conditionals
- •Decompose Conditional - Long if/else blocks
- •Replace Conditional with Polymorphism - Type-based switching
- •Replace Nested Conditional with Guard Clauses - Deep nesting
- •Introduce Null Object - Many null checks
For Method Signatures
- •Introduce Parameter Object - Repeating parameter groups
- •Preserve Whole Object - Passing multiple values from same object
- •Separate Query from Modifier - Method has side effects
- •Replace Constructor with Factory Method - Complex object creation
For Inheritance Issues
- •Pull Up Method/Field - Duplicate code in subclasses
- •Push Down Method/Field - Feature only used by some subclasses
- •Extract Superclass/Interface - Common features across classes
- •Replace Inheritance with Delegation - Subclass doesn't truly extend parent
Workflow
- •Identify the smell - What makes the code hard to work with?
- •Select technique - Use the selection guide above
- •Read technique details - Load the appropriate reference file
- •Apply incrementally - Make small, verifiable changes
- •Test after each step - Ensure behavior is preserved