I think I’ve started to turn a corner with TDD now as I found today’s exercise much more simple to approach properly. In fact, I’ve started to embrace the element of TDD which has, in the past, put me off (more on that below). That’s not to say I’m a complete convert (let’s let work start back up again and see what “real-world” stuff I manage to approach this way), but I’m certainly very much more comfortable with it.

Today’s 12 TDDs of Christmas challenge (code on bitbucket)was to create a simple template engine that accepts a set of key-value pairs and replaces the key placeholders found within the template with the values. It also has to throw an exception if there’s a key placeholder but no key within the set passed. Quite simple but I doubt anything I produce will be rivalling Razor just yet.

One of my pain-points with TDD – when I’ve tried it in the past – has been the concern that I should be implementing the minimum code required in order to pass each test. So, for a method that looks for multiple key placeholders and replaces them, after my first test (with one item), I should only replace a single item. Then, when a second test (with multiple keys) is added, I should alter the code to handle multiple items. I’ve always seen this as inefficient (adding a loop takes so little time) and have struggled to make peace with this when I’m writing code. After all, no-one particularly likes writing code multiple times for the sake of it and certainly not when you’re up against a tight deadline. I’ve always understood the reasoning for it, though.

Today was the first one where I’ve been quite strict. Not as strict as I perhaps should be, but far more than normal (e.g. this commit). I know it’s still something I need to work on (e.g. notice how I don’t only handle one key first time thorugh), but I’m getting better at it.

The result of today’s challenge was I fancied extending it slightly by passing in a custom expression extractor (i.e. a function that can be used to extract “firstName” from ${firstName}, rather than it being hard-coded. The resultant code change was actually quite clean.

I’m not there yet but I’m moving in the right direction.

Items in this series:

  1. 12 TDDs of Christmas (day one: Calc Stats)
  2. 12 TDDs of Christmas (day two: Number Names)
  3. 12 TDDs of Christmas (day three: Mine Field)
  4. 12 TDDs of Christmas (day four: Monty Hall, day five: FizzBuzz and day six: Recently-Used List)
  5. 12 TDDs of Christmas (day seven: Template Engine)
  6. 12 TDDs of Christmas (day eight: ranges)