When to refactor

· Code Quality


Refactoring is improvement without change to behavior. The moment it changes
behavior, it stopped being refactoring and became a rewrite.

The code that should stay

Code that:

Leave it. A refactor is not free—it is a bet that the improvement is worth the
risk.

The code that needs refactoring

Code that:

This code is expensive. Every change costs more than it should. Refactoring
pays for itself in the next change.

The refactor that goes wrong

A function that is confusing, so you refactor it to be clear. In the process,
you change the logic slightly. The tests still pass because the tests were
written to test the function, not to test the behavior.

The refactor changed the behavior and the tests did not catch it.

The safe refactor

Tests first. Run them. Change the code. Run them again. If they pass, the
behavior did not change.

If the tests do not pass, the refactor changed something and the change is
detected.

What I learned the hard way

A refactor without tests is not a refactor, it is a rewrite. Rewrites introduce
bugs. Refactors do not.

The question that matters

“Will this refactor make the next change easier?” If yes, do it. If no, the
code is fine the way it is.

The code that is hard to read but easy to change is better code than the code
that is nice to read but hard to change.

The purpose of refactoring is not beauty. It is to make future changes
cheaper. If there will be no future changes, there is nothing to refactor.

refactoring improvement judgement
last updated: