50. How do you refactor a function so it is easier to test?
MediumDebugging & production
Technical
Show model answer
Separate pure decision logic from side effects (database, network, clock, randomness). Pass dependencies in as parameters or constructor arguments (dependency injection) so tests can use fakes, keep functions small with clear inputs and outputs, and avoid hidden global state.
Then add tests around the existing behaviour before changing it (characterisation tests), refactor in small steps, and keep the tests green.