Published on

Red - Green - Refactor

Authors
  • avatar
    Name
    Seb
    Twitter

The Red-Green-Refactor Approach

The RGR approach is a methodology derived from Test-Driven Development.

The idea is to structure development in the following phases:

  1. Red

    We write our expectations first, usually via an automated test.

    Once the test is written, we can run it and see what happens.. This seems a bit useless, we haven't written any code yet, it cannot pass. But what if it passes because our assumption of the problem, or the implementation of the tests, or the setup of the test cases are wrong?

    Only if the tests we have written are really failing red, as expected, we have succeeded with our goal for this phase.

  2. Green

    Now that we have established our expectations, we can start to make things happen, and go ahead and implement the necessary code to make our test pass green.

    Following the RGR approach, we should only focus on making the test green. We should not focus on style or performance.

    Once our tests are passing and all is green, we can continue to the next phase.

  3. Refactor

    Now that we know our code is correct, we can work on improving it.

    This is the time we can consider things like code style (is it readable, maintainable, does it adhere to the code-base's conventions) and performance (can it be faster?)

Why this is a powerful approach

I very much like the RDR approach.

In the red phase, it makes you think about what you want to achieve. Developers like to develop, so sometimes they just start to write code, only to realize later that the problem is different from what they understood initially. By writing concrete test cases first, we focus on nailing down the problem with exact tests.

In the green phase, we can greatly benefit from the work we have done in the previous phase. At this point we do not have to think anymore about what to achieve but merely on about how to achieve it. The existing test cases enable a rapid feedback loop. After writing or changing any of our code, we immediately know if what we have done was correct or not.

In some companies, especially those focusing on pair programming, one developer would write the red phase code, while another would write the green phase code.

Summary

This approach can be very powerful. It might seem counter-intuitive and needlessly strict at first, but can make development more structured and efficient.