Monday, August 11, 2008

Joy of unit testing

(From about 2 weeks ago, late at night)

I was just vaguely napping and realized I was still thinking in my sleep about the php code I had just been writing. Though I barely even know php at all, it wasn't that hard to just guess at it because it was mostly like Perl. My thinking in Perl is a bit stuck. Today with Oblomovka I wrote out what I wanted my program to do, then he started writing tests. At first I didn't get it that the tests didn't run actually in the program. My thinking was inside out. I thought I'd run a bit of code, then run something that tested if it did it right, or that error/die statements would be sprinkled around. But as I saw what Oblomovka was doing it was like a light went on and I felt like everything I've written has been incredibly sloppy! Works fine, tells you if it doesn't work, but was like wearing shoes instead of making a road. Or the other way around.

It was really fun to write the very simple tests and then figure out how to send it the simplest possible thing to fake it out so that the tests would pass. So for example if you were writing a simulated ball game, you would not start by simulating a baseball game. Instead, you might vaguely sketch out what happens in a game. Then, you'd write a test that goes like, "Does a ball exist? If not, FAIL." You would watch it fail. It's supposed to. Then think of the smallest thing it needs to do to pass. Your program would then merely need to go, "Oh hai. I'm a baseball" and the test would pass. You'd write another test that goes, "Is there a bat?" and "Is a baseball coming at my bat?" As you write fake bats, balls, and ball-coming-at-you actions, the baseball game starts to take shape. All the tests have to keep passing. The structure of how to build it becomes more clear, in a weird way. This isn't quite the right analogy. I can't quite get into the way of thinking and end up just hacking quickly on ahead. But for a little while, I felt the rightness of this way of doing things.



Technorati Tags: , , ,

Digg this

2 comments:

sgtg said...

Do you realize you're doing TDD (Test Driven Development)? Don't take that question wrong please. You don't mention TDD, so that's why I'm asking. At any rate, ur doin it. And that's cool.

craig said...

As I'm still a relative of beginner in the programming world I always do tdd. and i know the feeling you get when things just click and you understand what needs to be done.