Index ¦ Archives

My Thoughts On Test Driven Development

When speaking to people who code, I have noticed a sharp divide between people who write tests for their code; also know as Test Driven Development (TDD) and those who do not. In the former the coder will generally write a test in the same language for each unit of functionality they intend to add to their project. In the latter, the coder will rely purely on outputting to the standard output with a print statement or some sort of logging functionality.

For example, lets work with a very simple example in Python. Let say we want to write a method which adds two numbers together called add

# method to add two numbers def addnumbers( num1, num2): return number1 + number2

Without writing a test you might test your code by calling your new shiny method and passing in two numbers, giving you:

# method to add two numbers def add( number1, number 2): return number1 + number2

print add(1, 2) print add('a', 'b')

Now these print statements can be seen as tests and you could write more print statements to check the behaviour of your code; for example, what happens with negative numbers or what happens when characters instead of numbers are passed in.

If you were coding with TDD in mind, these test would be written before the method was defined. In effect, you would be defining the behaviour that you want to see and then writing the code to meet that expectation. As you write a new test and then add the functionality that you are testing for, you would re-run all the tests. This has the benefit of ensuring that anything that went before, hasn't been broken, this is also known as 'backward compatibility'.

In my experience, when I began to code in a TDD style, I felt as though I was creating something more complete, that I understood the code and the problem better, and that I was making a professional job of it. It made a lot of sense. What you will end up doing however is writing more code in the beginning because of the tests. This may seem like overkill in the beginning but I think that in the long term you would waste less time in lengthy debug sessions, where you would pepper your code with 'print' statements and breakpoints.

I think that there is a place for both approaches however; if you want to code something quick and dirty like a use once piece of code or a quick hack, writing tests might slow you down. I can also see that TDD could be seen as too boring, not what a true hacker would do and be more the favourite of project manager types. As a final word, for those curious about testing in Python; you wouldn't normally use the print statements to write your tests, there is the assert statement and modules for this sort of thing, see; doctest, unittest & test. Why not give them a try.

© Imran Nazir. Built using Pelican. Theme by Giulio Fidente on github.