Possibility and Probability

Coding Python and making businesses…

3 May 2006

Unit Testing makes for better code

by Nick

Lately I’ve been trying to work more of a testing into the code I’m writing. I’ve read a lot about Test Driven Development, and while I think it is an interesting approach, it just seems like such overkill in many situations. For me I’ve found a happy medium by approaching my development in the usual ways (design, then code), but I’ve been trying to inject testing code at the earliest opportunity I can. I’m finding that the more I do this the better my code looks. So far the biggest difference I’ve seen is that I’m tending to write cleaner interfaces for my classes. This is because with the tests I’m trying to make sure the logic in the class is functioning correctly and sometimes it is nice to see what is going on in the middle of the process. A clean interface makes this task much easier, and as a bonus the cleaner interface allows the code to fit better into the rest of the code base because it is now there with a purpose instead of just being shoehorned into place. (Of course some people will point out that a good design process would eliminate this problem in the first place, but sometimes you just can’t get that level of detail in the beginning. Viva la refactoring!) The biggest benefit of unit testing is supposed to be finding bugs. While I do find bugs early with unit testing, I don’t think this is the biggest benefit I’m going to see. For me the biggest (and most unexpected) benefit so far has been discovering area where I can decouple (via better interfaces) my classes from each other. I’ve already seen one or two spots where during a refactoring I was able to get a lot of major work done quickly and successfully, and it is because the code was properly coupled with the rest of my framework. That was pretty cool. So, in short: Don’t be afraid to add some testing code to your project. You don’t have to go overboard with it, even a little bit can help out a lot.

tags: