Red Green Repeat Adventures of a Spec Driven Junkie

Test first - Refactor and Deliver Your Best Code

Another area where test first shines over code first: with good test coverage, you can refactor your code with confidence.

Remember the test driven development rule?

Write the smallest failing test first, then the smallest code to make it pass.

The code created using this method won’t be the prettiest - because you have layered on code here and there in an incremental manner.

That’s when refactoring comes in.

Refactoring is when the tests remain constant - no new tests, no changes to the test - and change the code to be prettier, smaller, tighter, optimized, etc. in a confident way.

This is the refactor loop:

  1. Make code change
  2. Run test suite
  3. If any test fails, revert code change
  4. Goto step 1

This process is best when done in a small incremental way. Just like when adding code when adding tests - the first draft of your solution.

The difference this time is that there are no new tests. You have “the whole picture” of the technical requirements through the tests.

As you refactor - you make your solution better. You create your final draft to submit to your team to review. Make sure you squash it all down so it’s nice and pretty.

You can skip the refactor step if the code is stellar or there’s a crazy deadline or something unexpected occurs. You can come back and refactor afterwards. Even with the code changes, you won’t have to re-deploy. Why?

You locked code behavior by having all the tests.

The refactored code may look different than the original. The tests guarantee the behavior of the code is constant.

Test first, code second, refactor third, and deliver your best code!