Buy JitterTed's TDD Card Game Here

Red-Green or Refactoring First?

Which came first, the chicken or the egg? The Refactor or the Failing test?

tdd

Originally published on . Last updated on .


When it comes to Test-Driven Development, we often see it as a cycle consisting of three parts: RED, GREEN, and REFACTOR.

Three circles in a triangular formation. A red one at the top labeled 'red', a green one labeled 'green' at the lower-right, and a blue one labeled 'refactor' at the lower-left. Arrows point from red to green to refactor and back to red.
Typical Red-Green-Refactor TDD Cycle

I think about the process as two high-level activities:

  1. Changing the behavior of the system via coded expectations: this is the RED-GREEN part of the cycle. We do this for “them”, i.e., the folks who asked us to solve their problem (or perhaps implement their solution) and make their lives better (we hope).

  2. Preserving the behavior and making the code easier to understand. Can also be adapting it to the next thing we’re about to implement, i.e., the REFACTOR part. We do this for us, the humans working with the code, to make our lives better; to increase the changeability of the system[1].

However, we don’t always need to start with a change in behavior (i.e., step 1), sometimes we start with making the code easier to work with via REFACTOR, which looks like this:

Three circles similar to the previous diagram, this time with the blue one labeled 'refactor' at the top, followed by the red one labeled 'red' at the lower-right, and the green one labeled 'green' at the lower-left.
Starting the TDD Cycle with Refactoring

TDD is a cycle, after all, with a choice of where to begin. Though I treat each time we land in GREEN and REFACTOR as safe stopping points (where I’ll try to commit to version control). This is related to “Small Steps” and “Ready Points” (GeePaw Hill), which I’ll talk more about in a future essay.

Over the next several articles I’ll dive deeper into these two parts: Change Behavior (the RED-GREEN part) and Increase Changeability (the REFACTOR part).

  1. Clarifying the Goal of Behavior Change
  2. Predicting the Failing Test
  3. Implementing the Feature

How do you think about the TDD Cycle? Let me know on Twitter or join my Discord to discuss this and other topics!


  1. Note that this is not the same as premature flexibility or speculative generality. ↩︎


Make Your Code More Testable™️

Don't miss out on ways to make your code more testable. Hear about new Refactoring techniques, improving the Test-Driven Development process, Hexagonal Architecture, and much more.

    We respect your privacy. Unsubscribe at any time.