JuniorProgramming skills

What is refactoring, and how do you make sure the code still behaves exactly the same afterwards?

The interviewer wants to know whether you can tell changing structure apart from changing behavior, and whether you have the habit of protecting yourself with tests. Refactoring means changing the internal structure of code so it is easier to read and change, without changing its outside behavior. Renaming a variable, splitting a long function into small ones and pulling repeated code into one place are all refactoring. Adding a feature or fixing a bug is not, because those change behavior.

A good answer follows this order:

  1. Have tests before you touch the code. If the code has none, write characterization tests: tests that capture what the code does today, even when that behavior is a bit odd. They don't ask "is it right?", only "is it different from before?"
  2. Work in small steps and run the tests after each one. When a test goes red you know which step caused it, because only one small thing changed.
  3. Don't mix refactoring with behavior changes. If you spot a bug halfway through, note it and fix it in a separate commit. Keeping the rename commit apart from the code-move commit also makes the review faster.
  4. Know what is an "inside name" and what is an "outside name". Renaming a local variable is safe. Renaming a field in the JSON an API returns breaks everything that reads that field, even though your code still compiles.

A concrete example makes the answer more convincing. Say you are cleaning up a small server that returns a list of orders. You rename the field khach to customer to match the rest of the code, and your characterization test on the server's response goes red at once, because the admin page reads exactly the khach field. Without that test, the bug would only show up when a user sees an empty column.

Bonus points: say when you would not refactor, for example when a deadline is close and that code is not what you are changing, or when you can't test it yet. Refactoring at the right time, in a small scope, fits a pull request that is easy to review better than cleaning the whole project in one go.