Red Green Refactoring
To truly understand the idea behind red green refactoring (RGR), its first important to appreciate the principles behind Test Driven Development (TDD).
TDD is essentially a very simple albeit absolutely paramount philosophy to coding. In fact to simply label it a philosophy would be somewhat of an indignity — coding is TDD and TDD is coding (in a good-practice sense at least anyway). The premise is simple — you write a code intending to fail, and then you modify the code to make it pass. Rinse and repeat to satisfaction. Simple.
RGR articulates that philosophy into three tangible steps:
The Red step — the first step where you kickstart the process by writing a unit test that you are certain will fail. In a testing environment this often returns a red failure message, hence the red connotation.
The Green step — revisit your failed code, study the failure/error message that underlies the code, and then make the necessary modifications so that your unit test will pass, or go green!
The Refactor step — with your unit test passing and satisfied that your code is functional, the next step would be to refactor or fix up the code to make it seem leaner, more aesthetic and most importantly — quicker to run. Principles such as DRY (Do not Repeat Yourself) apply here when considering refactoring.
Repeat until satisfied. That’s it!
So we know what it is and how it works, but the more pressing question is why bother?
The RGR is a circular process that functions as a tool for approaching a coding related problem. By constantly analysing and rethinking your hypotheses, the code will become less likely to contain bugs as you via the tests are able to react to problems as they occur.
Studies show that programmers who use the red green refactoring approach become more efficient and productive. Focusing on individual test cases and making them pass these tests eventually makes the code more smooth, functional and user-friendly.