Month: May 2009

You really shouldn’t test that

Posted by on May 22, 2009

 

You know, sometimes, you really shouldn’t test your code.

What?

Yes. You heard me. You shouldn’t test your code.

Well, let me explain that better. I recently took a course where I was paired with someone where neither one of us knew what it was that we _really_ wanted to do. We started to flush out an API for wiring up a hand rolled IOC automatically, and every time we did so, we hit a brick wall. The reason is that we kept trying to ‘test first’.

Don’t get me wrong, I am a complete advocate of test first development. HOWEVER, if you don’t know what the hell you’re doing, you can’t really test first. Being able to test first implies that you can think ahead of yourself and write something that does exactly what you know you need.

In our case, we kept wasting time trying to write tests that just didn’t work with how we NEEDED to do things. How did we solve this dilemma? We sat down and spiked out some code. Just hammered it out and got something working. Now, let me tell you, we wrote some pretty damn horrible and untestable (except via black box testing) code. However, what we did gain was an insight into the process and steps we needed to take to accomplish our task.

However! We didn’t keep that working code we spiked out. Once we had a spiked set of code and a solid idea of what it was we needed, we were able to test and rewrite the code we’d spiked in a much better, tested and well designed manner that would have taken forever if we’d just kept banging our heads against the wall.

To reiterate:

1) TDD with no idea what we were trying to accomplish = 3 hours wasted.

2) Spiking out some code, getting our heads around the steps needed, wiping it clean and restarting the TDD approach with an idea of what we needed to do = less than 1 hour to completion.

Remember, testing first doesn’t mean you should beat your head against a wall just to write a test before writing some code. Sometimes, in order to write a test, you need to write some code first. I guess some people will write tests afterwards, I personally prefer to rewrite, as I find I spend just as much time fixing the code when retrofitting tests as I do just rewriting it out.

In the end, you just need to remember that even if you’re doing TDD, you shouldn’t be afraid to spike out code. It’s the best way to learn and give yourself some direction.