2 min read

3 Not So Obvious Things I Learned From 10 years of TDD

3 Not So Obvious Things I Learned From 10 years of TDD

(This was originally published as a Twitter thread. I think it deserves to be preserved in a less ephemeral medium.)

One of my mentees already knows some TDD. So instead of talking again about red-green-refactor, we talk about some stuff that might not be obvious to beginners. Sharing some here:

#1 The Ratchet

This one is straight from @KentBeck ‘s TDD by Example and it’s one my favorites.

“Imagine programming as turning a crank to pull a bucket of water form a well. When the bucket is small, a free-spinning crank is fine. When the bucket is big and full of water, you’re going to get tired before the bucket is all the way up. You need a ratchet mechanism to enable you to rest between bouts of cranking. The heavier the bucket, the closer the teeth need to be on the ratchet.

The tests in TDD are the teeth of the ratchet.”

Kent Beck – Test-Driven Development By Exemple

Once we get one test working, we know it is working, now and forever. This is why lots of people say TDD makes programming fun. And that it brings peace of mind.

It allows you to unload o lot of the weight our mind has to carry.

And I suspect this is also why some people resist it. Some people seem to like the heavy mental load.

#2 Different Value at Different Times

[Don’t remember where I read this. If you know, please tell me.]

What is the real value of TDD?

  • Enabling safe refactoring and preventing regressions?
  • Nudging the code to better modular design?
  • Or is it the executable specification?

My answer: YES! All of those, but we get them at different times.

When we’re writing the tests, they are the first client of the code. The focus is on the API, not on the internal implementation. Simple and short tests require that the code is composed by loosely coupled modules.

When the tests run, they give quick feedback on the correctness of the code, allowing for fearless refactoring.

And when we read the tests, we know it is an up to date description of the code behavior.

These 3 benefits should not compete with each other. We can have it all.

#3 You need Fakes

Fakes are fundamental to TDD.

Mocks get lots of hate but I don’t think they’re inherently bad. They can lead to hard-to-change code if not used properly.

No need to know all the details of all the types of fakes. Just learn to stub and mock well.

# Bonus – Where to learn more