Red, Green, Refactor

TDD mantra

Merce Bauza
2 min readNov 14, 2018

Let’s get into what test-driven development is and how to develop using tdd with an example, that is always better to see and understand.

During the explanation, I will remind you some of the rules of TDD as they are very important to get optimal results using tdd.

In TDD, the development is an iteration that starts with the red phase, continues with the green phase and refractor and then starts again!

What does red mean in test-driven development?

Red is the representation of a failing test. In TDD, we always start writing a test and as we haven’t yet wrote any production code, the test will fail. The test will be Red! But we don’t have to worry because that behaviour is expected!

Remember rule 2 and just write enough code to make it fail, keep it simple and it will be easier to keep you focused on what you are trying to test and, eventually, to make it pass!

For example, we will write a very simple test:

public void createGame()
{
BowlingGame game = new BowlingGame();
}

Creating a game from the class BowlingGame()that doesn’t exist yet, would result into a compile error.

After the red, comes the green.

We need to write just enough production to make the test pass. Yes! Green is a passing test!

public class BowlingGame() {}

It will result in a very simple class.

No distractions or complicated code.

And the last step of the iteration is refactor.

Actually, if you have followed the rules of TDD, this phase might not be happening until the second or third iteration.

When you start to see the same code or similar pattern on your tests, it’s time to refactor it! good practice is to group the repeated code in a method and call it when needed, among other good practices.

When refactoring is good to start thinking on design patterns and how to use them in your code to keep it simple for your tests to pass.

Reflexion:

Using TDD is a way to make sure all your production code is tested and that you can make as many change as you want on your code, that you always know if you are breaking it! and if you do… you know exactly where to go to fix it! (the test that has failed has the clue!)

Simple and effective.

--

--