TDD with XQuery

Author: Dave Cassel  |  Category: Software Development

Today I had a complicated function to write. The framework we’re using for this project has unit testing built into it, so for the first time in a long time, I did the Test Driven Development approach: I wrote a set of tests, then wrote code to pass the tests, and then refactored. It felt good.

Writing Tests

By writing the tests first, I had to think through what I wanted the function to accomplish before thinking through how it would accomplish it. It sounds so logical when I phrase it that way. I thought of a few different interesting cases and set up my tests to reflect them. If I had gone the code-first route, I’m sure at least one or two of the cases wouldn’t have occurred to me until I was well into the implementation.

Writing Code

I stuck with the TDD principle of writing the simplest code that will work — I didn’t worry at first about making it elegant or fast. After a little while, I had an implementation that worked (passed the tests) but wasn’t real pretty or real fast. No surprise. But at this point I could do a check-in knowing that I had something that was at least workable.

Refactoring

Refactoring is a very important step in all this, of course. One reason I wanted to refactor is that my solution didn’t run very quickly. So I fired up CQ and ran my code with the profiler. That’s always the first step in making code faster, right? Crank up the profiler and let it tell you where you need to fix things. The profiler told me what areas to work on and the unit tests told me when I messed up the logic. Rinse, repeat, success!

TDD

I’ve used TDD before, but I’d gotten away from it in my work at MarkLogic because I didn’t have the tool support. XQuery is a relatively young language, and some of the tools I got used to in other languages aren’t as fully developed yet, but we’re making good progress. Now that I’m working with a framework that includes unit testing, I’m very happy to be able to use this approach again. I’ve missed it.

Tags: , ,

Leave a Reply