Capture behaviour before moving code
Choose a boundary you can observe: a public function, a response or a file transformation. Record representative inputs, outputs and side effects. Include an awkward case that earlier maintainers may have preserved for a reason.
A characterisation test records current behaviour; it does not prove that the behaviour is desirable. Mark suspected defects separately. Decide whether to preserve or change each one before a large refactor makes the difference hard to review.
Create one useful seam
Separate access to time, external services or persistent storage from the calculation you need to change. Prefer the smallest boundary that lets the test run deterministically. Avoid introducing an application-wide abstraction merely to simplify one test.
Extract a function or replace a duplicated branch in a separate patch from a dependency upgrade. Small transformations make it easier to identify the cause of a regression and to review whether the behaviour stayed the same.
Measure the change against the original contract
Run the baseline checks on the original implementation and candidate. Examine exceptions, ordering, rounding and transaction boundaries, not only the most common returned value. Keep the final diff small enough for a reviewer to follow.
Retain a rollback path for any changed deployment artifact or data shape. If the task now needs a schema migration or a new business rule, stop calling the whole change a behaviour-preserving refactor and add explicit acceptance checks.
Working sheet
| Boundary | Invariant to preserve | Small first change |
|---|---|---|
| Price calculation | Recorded rounding and discount order | Extract pure calculation |
| File import | Accepted columns and error format | Isolate parser from file access |
| Notification sender | Recipients and retry decision | Inject message transport |
| API handler | Status and response schema | Extract validation helper |
Questions about refactoring legacy code safely
Should I test private methods?
Prefer the smallest public boundary that exposes the required behaviour. Tests tied to private structure often need rewriting during the refactor they are meant to protect.
Can I refactor code that has no tests?
Yes, but first establish focused checks around the affected behaviour. If you cannot observe the result or control external effects, reducing that uncertainty becomes the first task.
How should I use the working sheet?
Download the CSV and replace the sample rows with evidence from your repository. Record a clear acceptance check and an owner for each item. Keep unresolved assumptions visible rather than treating the example as a completed assessment.
Sources and further reading
Examples are illustrative. They are not customer results, security guarantees, or a substitute for checking the documentation for your installed version.
