Main Content

Test Driven Development - a first example of principle in C

Archive - Originally posted on "The Horse's Mouth" - 2014-12-01 19:04:40 - Graham Ellis

If you're writing a substantial chunk of code, chances are that you'll want to split it down into manageable pieces. By doing so, you can make for re-usable code, for clearer code when you come to maintain your application, and for code that you can test section by section.

I'm going to encourage yu to go a stage further, though - I'm going to encourage you to write the tests before you write the code, and have the tests form the specification. As the code grows, and functioanllity is added, you can add extra tests to your test pattern and by rerunning your tests each time you add to or alter the code, and then testing will make sure you've not damaged something else.

There are packages and fucntions to help you write your test driven development softwares, and unit testing stuff to let you separate your tests, and to manage the results. However, today I was teaching "Learning to program in C" and those extra routines use code that's far too sophisticted on day 1, so I wrote some simple stuff directly in C.

Code to be tested - [here]
Include file (headers) - [here]
Test code - [here]

You'll note that I've printed out results all through the tests, but then sent a final status out to stderr. That way I can run the tests in a verbose mode, but if I just want to see if it all works I can redirect stdout.

  trainee@kingston:~/c_dec14$ ./tdd
  Result is 24.54
  Result is 0
  Result is 56.82
  Result is 1
  Result is 18.08
  Result is -1
  WORKED
  trainee@kingston:~/c_dec14$ ./tdd > /dev/null
  WORKED
  trainee@kingston:~/c_dec14$


All of our courses emphasise excellent coding practise and advocate its application from early on - our course schedule is [here]. The example here is a very basic one, but we'll establish this principle at the start of your course and then make sure you write good, testable code for ever.