The 3 Laws of TDD: Focus on One Thing at a Time

Shares

When I was first learning TDD, I’d try to get to the First Step (a failing test) by writing a fully-formed test. But it often took a lot fiddling to get that test to run and fail. Sometimes this was because the production code took several steps to set up. Sometimes it was because the test code wasn’t right.

One of the tricky parts of TDD is that we’re creating two streams of code in parallel: the test code, and the production code. Two things changing at the same time… that’s a hard thing to keep in your head!

The 3 Laws: managing parallel changes

That’s where the 3 Laws of TDD come in. They constrain us to change only one thing at a time. Here they are:

  1. You can’t write any production code until you have first written a failing unit test.
  2. You can’t write more of a unit test than is sufficient to fail, and not compiling is failing.
  3. You can’t write more production code than is sufficient to pass the currently failing unit test.

It’s hard to tell how they work just from reading them over. So watch the video above! I give a demonstration of the 3 Laws, as they play out in Swift. (Bonus: There’s a mock object, too.)

Try it yourself, see the difference

The next time you TDD a component, go ahead and do it the typical way, by writing the entire test. Observe:

  • How much test code you write in one shot.
  • How much production code you write in one shot.
  • How long you go without feedback.

Then try it again, but apply the 3 Laws. Notice the difference. Do you see how this activates even tighter feedback loops?

Remember, getting rapid feedback is a huge benefit of Test Driven Development. So why not dial it “up to 11”?

Give it a try. Then post your questions or observations in the comments below!

Did you like the video? Consider having me teach my TDD for iOS workshop at your company.

About the Author Jon Reid

I first experienced the joy of programming in junior high. But on the job, some of that joy was sucked away by seeing code my teammates were afraid to touch. Poor code led to fear, and fear led to our entire team being let go. I began searching for ways to improve code. I stumbled upon the first wiki, which was about Design Patterns, Extreme Programming, and Test Driven Development (TDD). I rediscovered joy on the job. I've now been doing TDD in Apple environments for 17 years. I'm committed to software crafting as a discipline, with the hope of raising you, my fellow programmers, to greater effectiveness and joy.

follow me on:
Disclosure: The links below are affiliate links. If you buy anything, I earn a commission, at no extra cost to you.
  • Alexander says:

    Thanks for this article! It’s very helpful.
    I am going to try this approach at my work.

    • Jon Reid says:

      Go for it, Alexander! If anyone questions you saying, “You’re taking a lot of extra steps,” try replying, “But each step is simpler.”

  • >