I’ve gotten into TDD at least a bit over the last few months. It has a learning curve, but I’m finding that it sometimes saves me from myself (and saves me time in debugging).
Part of my problem, like a lot of people, is that I sometimes over think things or fail to see something as being multi-purpose.
A perfect example was a code kata I started yesterday. It’s a fairly simple exercise – given a file with a list of numbers, take each number, reverse it, add it to the original number, and check to see if the result is a palindrome. Repeat until the number is a palindrome.
Simple stuff, really, but it’s a nice thought exercise.
It started off well. Decided to tackle the number reversal first. Since we’re dealing with data being snagged from a file, I decide to do the reversal with strings (since the data is already in string format, I can do most of the things required by the problem without having to typecast between string and int).
I name it ReverseNumberAsString since that name says what it does fairly well (it’s not the greatest name, but it’s the first function I’ve written in the solution, and we can refactor later).
Fast forward a bit to my writing a function to test if a number is a palindrome. This is where I start to over think things (and where TDD tells me I’m an idiot).
It’s been a long day and I’m a little fried, so the first solution that comes to mind is to set pointers at the front and end of the string and just walk them toward the center, comparing, until they reach the middle or find something they don’t match.
(Hey, I spent years doing C and C++ code. Give me a break)
I test a negative case first, and the test fails. I’d set the tail pointer to string.Lengtrh instead of string.Length-1 (it happens. I was fried.) I fix it, run the test, and it passes. Yay
Try to test for a positive case and the test fails. I go to look at the code to figure out why and, after a minute or two, I realize that I’m stupid, because I’ve already written the answer somewhere else in the code.
ReverseNumberAsString reverses a number that’s in the form of a string. No it doesn’t. It reverses a string. Period. I’m a dummy.
Rename the function to ReverseString like it should have been from the beginning and use that. Compare forward to backward. If it’s a palindrome, they should be the same thing.
Look at that. It works. Who would have guessed.
Thank you, Nunit, for making me stop and see that I’m being dumb.
Current mood - calmCurrent music - Dirty Vegas –