Thought on TDD

Andrey Maslennikov
2 min readApr 8, 2021

--

Kent Beck at the beginning of his TDD book gives a simple example how to follow the TDD approach. What was interesting to me is how he deals with duplications.

Kent’s approach to TDD is about two things:

  1. Write a failing test before you write any code.
  2. Remove duplications.

What kind of duplications he is talking about? For me, TDD was about 3 steps:

  1. Write a failing test.
  2. Fix the test by writing real code.
  3. Refactor.

Kent says “refactor to remove duplications”, so here we are aligned :) But what kind of duplications does he mean?

The example test is (I translated it to Python for simplicity)

def test_multiplication():
five = Dollar(5)
five.times(2)
assert 10 == five.amount

And the first working code is

class Dollar:
def __init__(self, amount):
self.amount = 10
def times(self, multiplier):
pass

Where is the duplication here? We don’t even have enough code for that. Or do we? Yes, we have duplication between the code and the test. And this duplication makes it impossible to write any new tests with different data because they will for sure fail.

This is very important to pause here and think. Refactoring is a mandatory step here. It is an essential part of writing code. It is not up to the next test to highlight issues in this full-of-hardcode code. No, it is time to refactor your code and eliminate duplication between the code and the test.

In my initial understanding, I’d start writing a new test and only then I’d do this refactoring (more of a change in this context). But Kent’s way makes more sense: each iteration ends up with a code of good quality. It works as expected, it is tested and it is refactored.

--

--

Andrey Maslennikov
Andrey Maslennikov

No responses yet