When should we Refactor in TDD?

Heaton Cai
3 min readJul 24, 2021

--

The TDD process requires us to repeat the following steps:

  1. Write a test for the next bit of functionality you want to add.
  2. Write the functional code that is just enough to pass the test
  3. Refactor both testing and functional code to keep it clean.
TDD

Without refactoring, the code would become harder and harder to be changed and the speed would also become slower and slower. Thus, refactoring is the most important step in TDD that allows us to go through the process at a stable and relatively fast pace. However, the refactoring skill is hard to learn. It requires a long time of deliberate practice to do it well. It gets even harder in TDD because the developers need to find the right time to do it in constantly changing code. Refactoring too early leads to over-design which stops us to easily add future requirements. Refactoring too late leads to a messy codebase that also stops us to easily make changes.

I’m going to introduce 4 rules that help us to identify the best time to refactor in this article. But before we start, let’s take a brief look at what refactoring is.

What is refactoring?

Definition: change the implementation code without changing the behaviours of the application.

Goal: remove code smells

The process:

  1. Find a code smell
  2. Apply refactoring methods step by step
  3. All tests pass without changing them (very important)
  4. Until the code smell removed
  5. Repeat 1 to 4 if there are more code smells
The Refactoring Process

Now we understand that refactoring starts from a code smell. So we can use code smells as the sign to start refactoring.

The best time to refactor in the TDD process

Here are the 4 rules:

  1. A refactoring starts if there is a code smell and ends when the code smell is removed, do not abort in the middle.
  2. Remove a code smell as soon as possible when you find it unless the direction of the refactoring is not clear.
  3. Remove a code smell within 3 baby-step iterations from the first appearance even the direction is still not clear (just pick one and change later or revert back if you find the direction you picked was wrong).
  4. No more than 3 code smells exist in your code at the same time.

By following the rules above, we will never leave our code in a position that is hard to be changed.

Summary

Keeping the code clean but not steps ahead is critical in TDD. It requires developers to apply refactorings at the right time. I hope these rules could help you to easily find them.

Further reading

--

--

Heaton Cai

16 years in the IT industry, passionate to share what I have learnt. All thoughts and opinions are original and maybe new. Free to share with the original link.