Scratch Refactoring For Code Understanding
by @quochungto
Guide a developer through throwaway refactoring — restructure code freely without tests to understand it, then DISCARD. Use whenever a developer says 'I don'...
Example 1: Opaque Algorithm in a Billing System
A developer needs to modify a 300-line calculateInvoice() method but cannot determine which lines handle tax calculation versus line-item accumulation versus discount application.
Scratch session:
1. Create branch scratch/understand-calculate-invoice.
2. Learning goal: "What are the phases of this method, and where does each phase begin and end?"
3. Extract blocks into named methods: accumulateLineItems(), applyVolumeDiscounts(), calculateTaxByJurisdiction(), formatInvoiceOutput().
4. Learning notes record: three-phase structure (accumulate → discount → tax), tax phase reads a hidden configuration object, discount logic has a special case for government accounts.
5. Delete branch. Learning notes survive.
Result: The developer now knows exactly where to add the new billing adjustment — in the accumulation phase, before discounts — and what tests to write first (a characterization test for the government-account discount case).
Example 2: Class with Tangled Responsibilities
A team inheriting a CustomerManager class (800 lines, no tests) cannot determine what it owns versus what it delegates.
Scratch session:
1. Create branch scratch/understand-customer-manager.
2. Learning goal: "What responsibilities does this class actually own?"
3. Rename fields and methods to reflect discovered purpose. Group by responsibility. Notice that 40% of the methods only touch a subscription sub-object — extract a SubscriptionHandler conceptually in the scratch.
4. Learning notes record: three hidden responsibilities (identity management, subscription lifecycle, notification dispatch). The subscription methods are cohesive enough to become their own class.
5. Delete branch.
Result: The team's real refactoring plan is now grounded: introduce a SubscriptionHandler class with characterization tests, extracted from CustomerManager using the Extract Class technique. The scratch session revealed the seam without committing premature structure.
clawhub install bookforge-scratch-refactoring-for-code-understanding