TDD is a software development approach in which test cases for every functionality are created and tested first to make the code bug-free and straightforward. The flow of TDD is to write the test, then later correct the failed test before finally writing new code. TDD helps the developer avoid a ‘wordy’ code as the written code aims to pass the test.
One of the most common approach of TDD is ‘Red, Green, Refactor approach. This approach helps developers to detach their focus into this three phase.
Red phase is all about what you want to develop. This is the cycle’s starting point where the purpose is to write a test that describes the further implementation of a feature. So that the test will only pass when the expectations are met.
Moving on to the Green phase, you will think about making your tests pass. The goal is to find a solution to pass the tests. Since this phase focuses on passing the test, you don’t have to worry about optimizing the implementation.
The last is Refactor Phase where you will improve your existing implementation. This phase is where you can begin to think of optimizing your code. Or, you can refactor your test as well if needed.
This concept of TDD might force you to spend more time code since you have to develop tests instead of just coding the software itself. Back to the title, Is TDD mandatory? Well, but here are some advantages TDD could offer to you :
- Build the right product: TDD ensures your system will meet the requirements that have been defined earlier that will be written on your tests
- Work Systematically: The tests would help you understand what problems need to be resolved based on the tests you have built earlier. The specific tasks will help you to work
- Better Cases Handling: Since the tests has been developed earlier, you have to make sure the tests are designed to cover the possible scenarios, including the edge cases. Thus, it can save your time to debug because your code is designed for all context-relevant scenario.
Despite all of the advantages TDD offers, it still has a some disadvantages :
- SOOO many codes to code: Sometimes, for a simple function in code, the tests need more lines of code than the original code.
- Time Consuming: For some beginners to a particular framework, understanding the tests is harder to understand the implementation itself. That’s why sometimes building tests is way longer than the actual implementation. Especially when you are forced to have 100% code coverage.
Well, Is TDD mandatory? Well, no one forces you to do so. TDD might help you understand your implementation easier by writing the tests first, yet you have to put extra effort into it. Of course, TDD is not bad at all, but it’s not a silver bullet. Be wise to write your test and know when to use it.