TDD – Test Driven Development or Test First – is a technique of creating software where you are writing tests for features before implementation. This methodology comes from times when we were using tapes for programming machines and gain popularity with extreme programming in 1990’s.
For the first time, I heard about TDD at my first conference, which I mentioned in previous post. During this presentation speaker told about benefits of this approach to writing software and showed the way how to encourage team to use Test First approach. Then during apprenticeship I participated in two TDD workshops which showed me practical way of using it. Now I try to use this technique whenever it is reasonable, for example in pundit.
In this post I will tell something about how TDD should work? Why to use it?
How to implement TDD?
TDD relies on three steps:
- Red – programmer writes a test for new feature. He does everything to make this code working – for example creating new class or function. Then he runs test and it should fail.
- Green – this step is for implementation. Programmer performs the least amount of work just to make test pass.
- Refactor – last step of iteration, helps to improve code quality, by removing redundant code, or improving naming of variables.
Benefits of TDD:
- Better code design- when programmer wants to use TDD he needs to write testable code, testable code means code with well structured dependencies, which in consequence helps make solution maintainable.
- Well tested solution – when writing test first, programmer think about new case of use at the beginning and then write code, in other way, in other way it is more likely that he forget to test something.
- Better code quality – third step – refactor helps to keep code clean and easier to read.
- Documentation – the side effect of test first approach. Tests helps to save time when we are searching for answer: “how should this functionality work?”.
Similar to TDD approach is BDD which I want to introduce in one of next post.