Refactor Large File
Goal
Reduce complexity safely without changing public behavior or letting code files grow past 400 lines.
When to use
Use when a file is too large, mixes responsibilities, contains duplicated logic, exceeds 400 lines, or is difficult to test.
When not to use
Do not use for greenfield features unless the feature requires extracting existing behavior first.
Inputs
Inspect the large file, direct imports/exports, tests, public interfaces, and nearby modules with similar patterns.
Workflow
- Identify existing responsibilities inside the file and note the current line count.
- Mark public API boundaries that must not change.
- If the file is at or above 400 lines, create a checkpoint before editing: copy the file to a backup path or save a patch diff that can be compared or restored later.
- Extract cohesive units, not random line ranges.
- Move related tests near the new owner when practical.
- Preserve imports and behavior incrementally.
- Run tests after each meaningful extraction.
- If the refactor stalls, compare against the checkpoint before changing strategy.
- Delete dead code once references are removed.
- Document important ownership changes.
Extraction targets
Prefer named modules such as invoiceTotals, userPermissions, orderStatusPolicy, or useGalleryFilters instead of generic utils files.
Validation
Run tests for affected behavior after each meaningful extraction, then the repo's size validation and any typecheck, lint, or build checks if exports changed. If the file started over 400 lines, compare behavior against the checkpoint before declaring the refactor done.
Final response
Report extracted responsibilities, changed files, validation commands, and compatibility risks.