Code
Untangle a god function
Break a sprawling function apart without changing what it does.
Fill it in
What to untangle.
How to break it up.
Run the suite after every step.
Your prompt
Untangle [the function or file]. Approach: decide Behaviour must not change. This is the whole constraint: a refactor that also fixes a bug is two changes wearing one diff, and neither can be reviewed. If you find a bug, note it and leave it. Read the whole thing first and write down what it actually does, including the parts that look dead. Then move in small steps, each one reversible. Run the suite after every step, not at the end. A refactor that breaks something in step two and is discovered in step nine has to be unpicked backwards. Name the extracted pieces after what they DO for the caller, not after where they came from. A name like validateAndNormalizeAddress is a name; one like processOrderPart2 is a bookmark. If the function has no tests, say so and pin its behaviour first. Refactoring untested code is editing in the dark.
Use Untangle a god functionOpens with everything above already filled in.
Why this works
One constraint: behaviour must not change. A refactor that also fixes a bug is two changes in one diff and neither can be reviewed, so a bug it finds gets noted and left. The other half is naming. Extracted pieces are named after what they do for the caller, because the default failure of an automated refactor is a chain of part1, part2, part3, which moves the mess without reducing it.
Questions
- What if the function has no tests?
- It says so and pins the current behaviour first. Refactoring untested code is editing in the dark, and it will not pretend otherwise.