What is Test Driven Development?
Test Driven development or TDD, is a technique of writing tests before you write any ‘real’ code. TDD can be summarized in three simple steps:
- Red– Only write new code if you have a failing automated test first.
- Green– After that, write the most minimalist implementation that passes the test.
- Refactor – Eliminate any duplication, make sure you follow coding standards set by the team.
Why Test Driven Development?
- Have you ever fixed a bug, only to find out that it broke something else?
- Have you ever been reluctant to drop unused code just in case?
- Have you ever felt like walking on fire as you made your way through an extremely complicated piece of code?
- Have you ever stared at a piece of code and struggled to comprehend what it does?
TDD can help avoid such pitfalls. It encourages developers to write small testable components. The tight feedback loop provided by tests can enhance developer productivity. As the code base grows and gains complexity, the benefit of tests really starts to become obvious. It allows developers to confidently work on complex parts of the application, without having to worry about breaking other things. If something goes wrong, the test suite will have their back.
A properly written test suite acts as documentation for the code. It will describe the expected behavior of each module. This is an extremely underrated aspect because documentation is generally not the first thing that we developers think about.
Lastly, the psychological impact it can have is immense. You feel a lot more confident about the code base.
It’s slowing me down
When starting out, TDD can seem to very slow but that is the case when developing any new skill. As you go on, it starts saving you more and more time. You’ll spend less time hunting down bugs, and more time producing quality code.
It’s tedious & complex
I’ll be honest with you, I was on this boat for some time. Testing seemed tedious and needlessly complex. I reluctantly gave it a go when working on an extension of Backbone.js. I knew I needed high-quality code to get approval from my team. Guess what? TDD saved me a lot of time, helped me avoid shipping bugs and made me a better, more confident developer. Now the first thing I do when working on a project is to add tests to it.
How do I implement TDD?
Keep it simple
Rather than writing large functions that try to do tons of work, break things down. Write small functions that each have a single responsibility and don’t interact with the outside world. A functional programming approach makes testing a lot easier.
Decouple your code
If your code is tightly coupled, testing can be an uphill battle. Components should know as little as possible about the components around them, and should be able to work independently.
If you aren’t already writing tests for your code, then start immediately. It is worth it!