Recently I had a chat with one of my former colleagues on Test Driven Development (TDD), when he mentioned that writing test code prior to writing production code (TDD) vs writing test code after the code is written should fetch the same results. I disagreed with his statement and to prove my point I gave him following example which seemed to make sense to him and I thought might be worth sharing here.
TDD enforces developers to write just enough production code to meet customer requirement and code that adds value to business. TDD refrains developers from temptation of writing too little or too much of production code thus ensuring the release of quality software.
TDD works on the principle where you write the test code first and all tests should fail by default as there is no corresponding production code. The developer then starts writing production code against the test code to make each test successful incrementally.
Consider the following simple example: Customer want to add 2 numbers and return the result of the addition.
In the traditional approach, the developer might come up with code that take 2 numbers as input, add them and return the result. The developer would then write test code against the written production code. There's nothing wrong with this approach, but the code is not full proof. Developer might have ventured and added additional frills to the production code that might not be needed. The developer might have also missed certain requirements in this approach that would result in error prone release of production code. The thought process here is write production code first and then test.
So how does TDD help?
Just like how Acceptance tests help validating the customer requirement, TDD helps set acceptance test criteria for the method being developed. In our example it's the add method. What could potentially be the acceptance criteria for add method?
- Can the method add 2 integers?
- Can the method add 2 floats?
- Can the method add 2 negative numbers?
- Can the method handle 2 large numbers?
- Can the method return error if only one number is passed to the method?
- And more…
TDD helps developer write code that is test focused where testing happens at a very granular level to meet the correct functionality. Once the functionality is coded to the requirements any attempt to hack the code would result in test failures as test code will catch such anomaly. The thought process here is write tests to accept the requirement and then code.