My son, Hardhik, started to learn programming using C++. He is freshman undergrad (1st year engineering). I thought of introducing TDD way of doing the programming so that he will get started the right way.
The program he wants to write is converting numbers into words (eg. 9,999 to “nine thousand nine hundred and ninety nine”). He went ahead and wrote the program without tests. He tested for the cases he could think of and felt the the program is rock-solid. Then I coached him to use TDD to write the same program. He wrote 38 test cases by the time the coding is all done. Then refactored the code to read better etc. To check how his first program worked, he ran the test suite on the first program and he got 25 test cases failed 🙁
I asked Hardhik to comment on what he felt about this exercise and this is what he said:
I wrote the same program in two ways.
The first time, I wrote it all the way down. I ran a few random tests with arbitrary numbers and pushed forward until the end. This program turned out to be extremely difficult to debug.
The second time, I used Test Driven Development. I wrote the program as I built cases. While it took quite a bit longer, in the end, it ran successfully for every single test case.
Till this day, that first program still does not work for many test cases, and it is difficult to even attempt to debug. Meanwhile, by the time I was done with the second program, there was practically no debugging!
As a beginner, this methodology has given discipline and structure to my coding process, has improved the readability of my code, and has made programming more efficient.