Make the change easy, then make the easy change
Key takeaway: Before each change, ask whether a behavior-preserving refactor would make the diff smaller, and if so, ship that refactor first.
Do the refactor before the feature, not during it, and ship them separately. Kent Beck’s version is one I quote at least once a month: “make the change easy (warning: this may be hard), then make the easy change.”
Say you need to add Slack as a notification channel, and the if email ... else sms branch that picks a channel is copy-pasted in four places, each slightly different.
If you clean it up while adding Slack, the reviewer gets 300 changed lines and has to find the dozen that change behavior. If it breaks in production, reverting the feature pulls the cleanup out too.
So clean it up first. Collapse the four copies into one Notifier.deliver(user, message) with no behavior change, and get the tests green. Now Slack is one new branch in one place, and the feature diff takes a minute to read.
Keep them in separate commits at minimum:
refactor: extract Notifier.deliver from four call sites
feat: add Slack notification channel
If the refactor is more than a few dozen lines, make it its own pull request and merge it first. The reviewer of a refactor only has to check whether everything behaves exactly as before. If you had to change a test’s assertions, it changed behavior, and that part goes with the feature. Later, git bisect lands on a small commit with one purpose, and reverting the feature leaves the cleanup in place.
Pay attention to the parenthetical in Beck’s quote. The refactor is often the hard part, so do it while behavior is held fixed and the tests can tell you when you get it wrong. That’s why good test coverage is a speed multiplier.
One caution: refactor toward the change in front of you. Restructuring for a change you only imagine is future-proofing gone too far. If it won’t make the diff you’re about to write smaller, leave it.