DCSIMG
Unit Testing is Fun - Doron's .NET Space

Unit Testing is Fun

As I've said in a previous post, I've been playing with unit-testing lately, trying to write up some classes and tests for them as I go along. I found this to be a really enjoyable experience. The tests help me understand what's going on in my code better, and they actually make me write better, and more correctly-structured code. Coupled code with too many dependencies is hard to test - by having to write tests as I go along I somehow force myself to think of a better design.

This also made me feel like up until now I was, with lack of a better expression, "programming on thin air". I had been writing lots of code, which depended on different classes, which depended on even more code, and I had no idea, no 'proof' that any of this even works. It is similar to trying to perform some mathematical calculation by relying on theorems that were never proved. There is no reason for the calculation to be right, and for all purposes it is utterly wrong. Doing this in a calculus exam will get you 0 points, but in developing software without unit-tests this is exactly what we do.

Now, I'm not saying that unit-tests are mathematical proofs. We can only test some of the values in some situations, when proofs are for all values in all situations. Still, if your tests are good and thorough enough, they can come pretty damn close, at least enough for you to feel that the ground you are standing on is stable.

About the TDD "Write tests before you write the code" approach, well, I'm still not quite sold on that. The problem is that in order to write the tests, even just to start, I've got to have a pretty good idea, in my head, of the design of my classes and interfaces. But many times, especially in the more complex scenarios, I have no idea how the code is going to look like when I start writing it. I start coding, then I refactor again and again - methods become classes, classes become interfaces, names change constantly. If I had to maintain working tests all this time, there would be hell to pay. Once the structure of the code stabilizes (which usually happens after a few hours), and I have a pretty solid idea of the final design, I can start writing the unit tests and the rest of the code. But maybe that's just me.

Published Saturday, February 24, 2007 9:35 AM by dorony
תגים:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: