Code bugs can be considered a programmer’s nightmare. Especially if your code consists of hundreds or more lines, you have to check every line in your code to find the error and which part needs to change so that your program works as intended. But, there’s a way to detect bugs early and a way to avoid getting a bug. That is Test-Driven Development(also known as TDD).
What is TDD?
Test Driven Development is an approach in software development where in creating a product, a developer is required to make a test before implementation of code.
There are some benefits that you can get if you use TDD:
1. Code flexibility and easier maintenance
2. Better program design and higher code quality
3. Save project costs in the long run
4. Team collaboration becomes more efficient by modularizing code (separation of concern intensifies)
Implementation of TDD
Test-Driven Development itself is a cycle.
Three stages make up the process are RED, GREEN, and REFACTOR.
Red stage is the stage where we write tests with purposely failed the test.
There are 5 rules to writing a test called F.I.R.S.T:
1. Fast: Tests should be quick so developers can find the problems and fix them easily
2. Independent: Tests should not set up the condition for another test
3. Repeatable: Tests should be able to run in various environments
4. Self-Validating: Tests should have output either pass or fail
5. Timely: Tests should be written before the implementation code that makes the pass test
It is my example of how to implement TDD in PPL. I was going to create a PBI for showing a list of trips so I wrote the test first. The code for the test:
The thing is, when we wrote this test, the implementation code doesn’t exist yet. So, the test will fail. Therefore, we expecting greeted by the red X when we pushed this piece of code into our repository.
Green stage is the stage where you will be writing codes in your main program to pass the tests that were made. After done with writing tests, now we can write the implementation. Here’s the implementation code from my previous test:
We then step into the GREEN phase where we actually implement the feature and pass the tests. Therefore, we expecting greeted by the green checklist when we pushed this piece of code into our repository.
Refactor is the stage you able to do minor changes to your code. It means applying clean code and not changing your code so that it fails.
There are unused comments that make smells code. Following the clean code rules, I deleted that comment.
After being forced to use it for some years, I’m convinced that TDD is a good approach. It makes sure our code suits the acceptance criteria, so one step closer to mark our task as done.