consolidate-before-refactor
Consolidate scattered logic into atomic operations before removing code to prevent race conditions and coupling issues.
Consolidate Before Refactor
When refactoring code that handles state changes across multiple locations, consolidate the logic into a single atomic operation before removing the scattered implementations. This prevents race conditions and tight coupling.
Steps
Identify scattered logic: Find all places where related state is modified (e.g., position updates, deletions, cascading changes)
Create atomic operation: Build a single function/hook that handles all related changes as one unit
- Use transactions or batch operations when available
- Ensure all dependent state updates happen together
- Return a single result that can be used by all callers
Migrate callers gradually: Update call sites to use the new atomic operation instead of scattered logic
Verify atomicity: Test scenarios where operations might race (concurrent deletes, rapid state changes)
Remove old code: Only delete the scattered implementations after confirming all callers use the consolidated version
Example Pattern
❌ Before: Scattered updates
- Delete function modifies position A
- Cleanup function modifies position B
- Caller manages both calls
✅ After: Atomic operation
- Unified hook/function handles position A + B + cleanup in one RPC call
- Single source of truth for the operation
Tips
- Use your IDE's refactoring tools to find all references safely
- Add tests that verify atomicity before/after the consolidation
- Document the atomic contract (what happens together, what's guaranteed)
- Consider using transactions or batch operations in your backend