--- name: refactoring-patterns description: Refactor code for clarity — extract method/class, rename, replace conditionals with polymorphism, remove duplication. Use when adding features to hard-to-understand code or paying down technical debt. license: MIT --- ## What I do Apply proven refactoring patterns to improve code structure. Know when and how to use each pattern. ## Essential Refactoring Patterns ### 1. Extract Method Use when: Function exceeds 20-30 lines, multiple nesting levels, comment explains a block. ### 2. Rename Variable/Function Use when: Name is unclear or misleading. ### 3. Introduce Parameter Object Use when: Function has 4+ parameters that form a natural group. ### 4. Replace Conditional with Data Use when: Complex if/else or switch statements, behavior differs only by data values. ### 5. Move Function Use when: Function used more in another module, uses more data from another module. ```rust // Move to where it's used most mod customer { impl Customer { pub fn total_spent(&self) -> f64 { self.orders.iter().map(|o| o.total()).sum() } } } ``` ### 6. Inline Function Use when: Function body is as clear as its name, trivial wrapper. ### 7. Replace Magic Numbers Use when: Number has special meaning, appears multiple times, or might change. ### 8. Extract Variable Use when: Complex expression hard to understand, used multiple times. ### 9. Remove Dead Code Delete: Unused functions, variables, parameters, commented-out code. ### 10. Replace Loop with Iterator Use when: Loop builds array (use map/filter), finds item (use find), checks condition (use some/every). ### 11. Pre-Pass Optimization Move invariant work outside loops. This pattern took a grass algorithm from 30 seconds to interactive. ```rust // Bad: Expensive work inside loop for point in &points { let entities = world.gather_entities(point); let mesh = entities.find_mesh(); test_triangles(mesh, point); } // Good: Pre-pass let entities = world.gather_all_entities(); let mesh = entities.find_mesh(); for point in &points { test_triangles(mesh, point); } ``` ### 12. Data-Oriented Design (ECS vs OOP) Use composition or ECS instead of inheritance hierarchies. ```rust // Bad: Fat struct with unused fields struct Entity { entity_type: EntityType, health: i32, // Only some entities use fuel_level: f32, // Only some entities use position: Vector3, } // Good: ECS - components are simple data structs struct CombatComponent { entity: Entity, health: i32, damage: i32 } struct FuelComponent { entity: Entity, level: f32 } struct TransformComponent { entity: Entity, position: Vector3 } ``` Use when: Entities need different property combinations, performance matters, want runtime composition. ### 13. Avoid Inheritance for Code Reuse Inheritance creates tight coupling. Prefer composition. ```python # Bad: Inheritance just for reuse class Car(Vehicle): pass # "I am a Vehicle" # Good: Composition class Car: def __init__(self): self.movement = Movement() self.horn = Horn() ``` Use inheritance only for true "is-a" relationships. ### 14. Draw Boundaries Around Operations, Not Objects Think about what operations you need, then design boundaries. ```rust // Bad: Boundaries around "objects" struct User { orders: Vec, // What if you need to email many users? } // Good: Separate data, separate systems fn email_system(users: &[UserData], templates: &EmailTemplates) fn spending_system(users: &[UserData], orders: &[OrderData]) ``` ### 15. Minimize Boundary Surfaces Every boundary creates communication cost. Boundaries prevent optimization. ```rust // Bad: Virtual dispatch prevents optimization trait Animal { fn speak(&self); } fn process_all(animals: &[Box]) { ... } // Can't batch // Good: Separate data from functions enum VoiceType { Dog, Cat } fn process_all_voices(voices: &[Voice]) { ... } // Can batch, inline ``` Add boundaries only when: different teams, security, physical constraints. ### 16. Don't Accumulate Delegations When adding new code, remove or consolidate old code. Don't just add more ways to do the same thing. ### 17. Clean Code Has Performance Costs - Virtual (vtable): 35 cycles/shape (1x baseline) - Switch: 24 cycles/shape (1.5x faster) - Table-driven: 3 cycles/shape (10x faster) Using "clean" code rules can erase 12-14 years of hardware progress. ```rust // Clean but slow: Polymorphism trait Shape { fn area(&self): f32; } fn total_area(shapes: &[Box]) -> f32 // Faster: Switch enum ShapeType { Square, Circle } fn get_area(shape: Shape) -> f32 // Fastest: Table-driven const COEFFICIENTS: [f32; 2] = [1.0, PI]; fn get_area(shape: Shape) -> COEFFICIENTS[shape.type as usize] * shape.width * shape.width ``` **When clean code IS appropriate**: Performance doesn't matter, simple CRUD, polymorphism needed. ### 18. Performance is an Ecosystem Concern Slow code compounds through dependencies. Your tools are built by others whose slow tools slow you down. ### 19. Upstream vs Downstream - Position: Upstream = Shallow in call stack, Downstream = Deep in call stack - Role: Upstream = Control state, Downstream = Derive effects - Example: Upstream = Business logic, Downstream = Rendering, APIs Downstream should NOT introduce state machines. Be immediate mode, not retained mode. ```rust // Bad: API introduces retained mode enum UserOperation { Create, Update, Delete } client.manage_state(); // Client must track state! // Good: API is immediate mode fn create_user(user: User) -> Result fn update_user(id: String, user: User) -> Result ``` --- ## Deep Modules From "A Philosophy of Software Design": **Deep module** = small interface + lots of implementation ``` ┌─────────────────────┐ │ Small Interface │ ← Few methods, simple params ├─────────────────────┤ │ │ │ Deep Implementation│ ← Complex logic hidden │ │ └─────────────────────┘ ``` **Shallow module** = large interface + little implementation (avoid) ``` ┌─────────────────────────────────┐ │ Large Interface │ ← Many methods, complex params ├─────────────────────────────────┤ │ Thin Implementation │ ← Just passes through └─────────────────────────────────┘ ``` When designing, ask: - Can I reduce the number of methods? - Can I simplify the parameters? - Can I hide more complexity inside? --- ## When to Refactor ### Before Adding Features - Code is hard to understand - Adding feature would make it worse - Tests are hard to write ### After Feature Complete - Clean up as you go ### Code Smells - Long function: Extract Method - Duplicate code: Extract Method, Move - Primitive obsession: Parameter Object - Switch statements: Replace with Data - Magic numbers: Replace with Constants - Rigid inheritance: Data-Oriented Design --- ## Refactoring Safety ### Before - [ ] Tests exist (or write first) - [ ] Code in version control ### During - [ ] One change at a time - [ ] Run tests after each - [ ] Commit working state ### After - [ ] Tests still pass - [ ] Code more readable --- Use these patterns to systematically improve code quality.