The 3 Rules of TDD (Plus bonus rule)

March 1, 2021

“Uncle” Bob Martin authored the Three Rules of TDD, which is enough to get started with TDD:

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

With these rules in mind, it’s pretty clear that writing all of your tests up front is not TDD.

It’s also worth noting that there’s no rule that you must use TDD for non-production code (although of course you’re free to do so, if you feel it’s a benefit!)

The fourth rule, which Kent Beck includes in his book Test Driven Development: By Example, and I think it’s worth including, too:

  1. Refactor.

That is, once you’ve written a test, and code sufficient to make the test pass, look for any reasonable refactoring to do on your code and your tests. Remove duplication. Make it more readable. Improve performance.


Related Content

Why "Consider refactoring this" comments are silly

Code is always subject to refactoring when the need arises. Adding a comment to that effect is just noise.

How can I eliminate technical debt?

You can't eliminate technical debt. Nor should you want to. But where does that leaev us?

Adventures In DevOps 095: Dev vs DevOps: Which Will You Choose?

Jillian, Jonathan, Will, and Chuck discuss where the line is between Development and DevOps and what the difference is. They also get into the value of each and when crossover is likely to occur.