An Afternoon with TDD
I spent most of my afternoon writing a class using Test Driven Development and it still astounds me that most people don’t do this. For me, at least, it’s the easiest and fastest way to create quality code. Note the word “quality” there — I could sling code out faster, but it wouldn’t be quality.
Getting started with TDD is really pretty simple. I wrote a class that extends JUnit’s TestCase and created one test. In that one test, I wrote the results that I wanted from the code. Of course, when I executed the test, it failed — because I hadn’t written the actual working code! After it failed, I started working on my method on my new business object. When I wrote a little, I executed the unit test again. If it passed, I moved to the next test (which tests for methods and logic I hadn’t written yet). If not, I kept working on my method until it does.
This seems really simple, and it is. But why do I think it’s so powerful? Because it makes you concentrate on little sections at a time. When you say, “After this method call, my object should look like X” so that’s how you write yours tests. It’s looking like Y instead? Well change your logic — because in your test you say you want X. Once I get my tests down, I rarely change them. Sometimes I will say, “Yeah, I think I may need to have the data look like Z than X” so I change my tests first and then change my object. Because my tests make up my contract.
This method works great for code you are writing from scratch, but what if you are working already-existing code that doesn’t have any unit tests? A good way to learn about how it works is to write unit tests for them, but that can take a long time. But I don’t have any further suggestions. Does anyone out there have any?
