/ refactoring

Refactoring first vs change first

One of my favorite Kent Beck, saying is the following:

for each desired change, make the change easy (warning: this may be hard), then make the easy change

However, there are cases where we can try to make the change easier, and actually make it harder. Sometimes it is easier to make a mess and cleanup afterward than to cleanup and keep clean.

When doing code changes, I see two scenarios:

  1. "Refactor first" - do refactoring, then implement change
  2. "Change first" - implement change and refactor afterward

What happens when you the order wrong?

If you go with "Refactor first". The risk is that your refactoring can make the change more challenging. You can lose yourself in refactoring and forget why you started.

If you go with "Change first". The change might be hard, and you lose a lot of time trying to make it. You might get tired after the change and decide there is no need to leave the code clean.

How to pick an order?

"Refactor first" is done when the change will involve changing in multiple places - a.k. change is hard. Your refactoring goal is to make the change easier. You use the change as an anchor for the refactoring.

"Change first" is done when change can be done by just adding 2-4 lines of code, and it leaves the code messy. You are refactoring to make the code more readable.


The idea here is to think about what to do first, so you don't double or triple your work.

If you have any questions or comments, you can ping me on Twitter.