Mike Hogan
Mike Hogan

Reputation: 10583

Red, Green, Refactor: refactor after each test case, or once entire test suite is fleshed out?

Write-ups of the Red,Green,Refactor (RGR) workflow in TDD suggest you get green quickly by writing "sinful" code if need be (Kent Beck said "quick green excuses all sins" in TDD by example), and then refactor to improve the design. I am unclear on when best to do the refactor step.

Lets say I am producing a BookByIsbn REST service. I may produce test cases in the following order (just for the sake of discussion)

"produces 404 (not found) if book does not exist"
"produces 400 (bad request) if isbn is invalid"
"returns 200 and entity if book found"
etc

Literal interpretation of RGR seems to suggest that I refactor after quickly getting each test case green. But this can lead to several times refactoring to a design that gets invalidated by the next test case. I sense delaying the refactor step until the full test suite is green, when I have full visibility of everything the service must do, is a more effective way to perform TDD.

So, the question: Is RGR best practiced by disciplining ourselves to refactor after each and every green, or is delaying the step until more requirements surface more effective?

Upvotes: 2

Views: 153

Answers (1)

Jon Reid
Jon Reid

Reputation: 20980

  • Refactor on each and every green.
  • Refactor both production code and test code.

This does mean that sometimes a design is very transient. But it means the code is always the best expression you have for the coded requirements at the time (the tests, as they grow).

Upvotes: 8

Related Questions