How can I refactor repeated function code without changing its behavior?
Quick answer
Extract repeated code only when the duplicated parts truly do the same job. First record what the current code returns for ordinary and boundary inputs. Then move the shared logic into a small helper, replace one copy at a time, and rerun the same checks. Keep differences in inputs or side effects outside the helper, and compare the refactored output with the original before removing the old implementation.
The question, the details, the next step.
A practical checklist
Confirm the repeated code has the same inputs, output, side effects, and conditions.
Record current results for ordinary, empty, boundary, and differing-case inputs.
Extract the smallest shared operation into a clearly named helper.
Keep intentional differences and caller-specific work outside the helper.
Replace one call site at a time and compare the same checks after each change.
Check relevant side effects and error behavior, not just returned values.
A few more useful answers
Should I extract code that appears only twice?
Not automatically. Extract it when the duplicated behavior is genuinely the same and a helper makes the code easier to understand or maintain; otherwise, two clear copies may be safer.
What if the helper needs several options to support both copies?
Pause and check whether you are combining distinct behaviors. A helper with many switches can hide the original differences; keep separate logic or extract only the smaller shared portion if that reads more clearly.
Do matching output checks prove the refactor is behavior-preserving?
They provide evidence for the inputs and observable behavior you checked, not every possible case. Add checks for relevant edge cases, side effects, and errors, and use the checks available in your project.
