Red Green Refactor


Red Green Refactor is the Agile engineering pattern which underpins Test Driven Development and may be used in other Programming practices

Red Green Refactor is characterized by a “test-first” approach to design and implementation, it utilizes very short Iterations to minimize leap-of-faith assumptions.

Red Green Refactor generally follows this pattern:

  • Design a test. Before any implementation work is done, the conditions to be met are specified. What is the expected output or result?
    • This may be asserted by example, e.g. a test for a proposed function sqrt(x) may be designed as sqrt(4) => 2.
    • Edge cases may also be exercised, e.g. sqrt(0) => 0,
    • as may valid variations on terms of interface contract, e.g. sqrt(2.25) => 1.5.
    • Invalid cases may also be tested, such as sqrt(-1) => Error.
  • Run the test. Since no work has yet been done to satisfy the test, it may reasonably be expected that the test would fail were it to be run. A failing test is commonly shown as a red bar in an Integrated Development Environment. However, it must not be assumed that such a test will in fact fail. For example, it is possible that the test may have been incorrectly designed, such that it can “pass” (green) even without the implementation of a solution. Also, the test may pass (green) if the conditions are already satisfied, and additional work does not, in fact, need to be done. Running the test first, in order to verify the hypothesis that there will be a red bar or similar indication of test failure, is the “Red” step inRed Green Refactor.
  • Write the code and test again. The missing feature should be implemented so that the test will now pass (green). Note that the “law of parsimony” should apply. Just enough code should be written to satisfy the test and no more. It’s also important to execute all other tests to make sure that the implementation has not caused existing functionality to fail. The code should be revised until all tests execute successfully. This is the “Green” step in Red Green Refactor.
  • Refactor the code. Now that the functionality is in place, it can be optimized for improved readability and maintainability. Any expedient design decisions should be revised so that technical debt is not incurred. Better design patterns may be leveraged, and the quality of the code improved as per the team’s coding standards. After the code has been refactored in this way, the tests should be re-run. They should still come up green, thereby indicating that refactoring has not compromised the functional correctness of the implementation.

Red Green Refactor is a form of Refactoring

More Information#

There might be more information for this subject on one of the following: