August 13, 2011

Bugs

Don't you just hate bugs? Now, I'm not talking about insects here. I'm talking about the little computer bugs, and I have to say I've grown to appreciate Test Driven Development (TDD). I'm not referring to extreme programming, which is a type of TDD, but the whole concept of testing your code before you even deploy it. I know so many people think some things are trivial and it wouldn't be useful. For the most part, you probably are right, but the beauty of it is for large-scale systems. Let's also not forget how handy it can be when trying to modify old code.

I was overhauling how input is handled in my framework, essentially gutting and redoing roughly 1500 lines of code. Which, isn't really a whole lot, but certainly has room for error. I decided to quickly draw out my basic plan, followed by rough implementation and then continued to develop and refine it with test code. I caught 4 little bugs before I had even executed the code once because my tests caught some really silly mistakes. Later, during my deployment of the new code into the framework I ran the program and it didn't work and the program was doing something weird. I looked at the code and couldn't find what could have possibly caused it, especially when my tests I ran earlier proved that the case should work. So, for good measure, I ran the tests again, and guess what? I got failures. It took me a bit to figure out the root cause, which ended up being one line of code that I had added during the transition for "convenience". I don't have tests for a good majority of my code, but this little experience has made me value how all the time and effort up front has paid off later. It would have taken me hours to find that one line, which I had completely forgotten about, instead it took me minutes.

Honestly, you don't write tests to make sure your code works. That is just a benefit of writing tests upfront. The real reason is so that when you go and change your code, you can check to see if you broke something without even having to run the program. It is more just for a convenience to save yourself time when you want to change something. If you are writing code that you know you're never going to touch again, then don't bother with the tests. However, if you think there might be a chance you'll change it later, probably best just to go and write some tests that covers the basic cases of how the code will run and a few odd cases. Obviously, if you were really serious about the tests you would analyze the code and figure out your input domains and boundary conditions, heck, you might even see how your code coverage is. Code coverage is another topic, and is really a double edged blade when used incorrectly.

The short version: If you write code that you are going to change down the road, write some unit tests and save yourself tons of time later.

No comments :

Post a Comment