TDD Refactoring – Uncle Bob’s Rules vs Classic Cycle

refactoringtdd

Uncle Bob says in 'The Clean Coder', chapter 5 'Test Driven Development':

  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.

Where is the place for refactoring?

Best Answer

Robert C. Martin 'The Clean Coder', chapter 5 'Test Driven Development'

For what it is worth, you'll see those same rules on his website: Three Rules of TDD.

Where is the place for refactoring?

It happens on a different cadence. See The Cycles of TDD.

Second-by-Second nano-cycle: The Three Laws of TDD.

the goal is always to promote the line by line granularity that I experienced while working with Kent so long ago."

vs.

Minute-by-Minute: micro-cycle: Red-Green-Refactor

This cycle is typically executed once for every complete unit test, or once every dozen or so cycles of the three laws. The rules of this cycle are simple.

  • Create a unit tests that fails
  • Write production code that makes that test pass.
  • Clean up the mess you just made.

For comparison, consider how Kent Beck described TDD in Test Driven Development by Example.

  1. Quickly add a test
  2. Run all tests and see the new one fail
  3. Make a little change
  4. Run all tests and see them all succeed
  5. Refactor to remove duplication

In other words, what Beck describes is the Red-Green-Refactor workflow - write the whole test. That introduces a bunch of compiler errors (because the examples in those days were written in Java). Write a little bit of code to fix each error in turn. Now you have a failing test (RED). Write a little bit more code to make the test pass. Now you have an implementation that satisfies all of your tests (GREEN). Now clean up the mess (REFACTOR).

What the three laws of TDD are giving you is a nano workflow within RED-GREEN. You tick-tock between writing test code and writing production code, fixing each error as it comes, until the your implementation delivers the correct behavior.

From what I can tell, where the nano-cycle really stands out is in those places where you are extending the system under test; adding a new method, or a new class. Those are the cases where you see compiler errors that need to be fixed. In the case where you are creating a test to evaluate a changed behavior, there's little to distinguish the nano-cycle from test calibration.