On Test-driven development

Test-driven development is a technique at the basis of Agile software development and is, in my view, the most important contributing factor to creating high-quality results.

The primary goal of Test-driven development (TDD) is to force a quick feedback loop that forces you to write in small steps.

TDD imposes writing first a test for a code that hasn’t been written yet and then writing enough code to make it produce the desired output and nothing more.

Test -> Code -> Refactor

The process of TDD follows a strict cycle:

  1. Write a test that will fail
  2. Write just enough code to make it pass
  3. Refactor both test and code to a good standard

Refactoring doesn’t only apply to the code written for the test; sometimes, a better architecture will emerge, and a more significant set of changes will be required. Be ruthless in refactoring, the test suite is there to spot any error.

Start with a plan

Writing TDD doesn’t mean starting without a clear idea of what to build. Start by writing a spec of what the result should look like, it will help write the tests.

That spec will probably not resemble the one we come up with at the end, and that’s ok; the final result will be much better.

Start from the end

Writing a good test should start from the end. Force yourself to write the API or result and walk backwards towards a way to get there.

Design your code the way you want it to be used, not how you need it to be tested.

Don’t ask too much

Each test should bring the code closer to the final result. Start from the most basic behaviour and work towards the end goal by satisfying all the requirements necessary to achieve it. By avoiding writing the complex tests, the code will gradually grow, giving you time to refactor after each test quickly.

Books

I recommend these two books to understand how to reason about TDD