The advantage of testing first

I really like Test-Driven Development. Think about what you need to write, write a test (that fails), then make it pass. Repeat. Refactor.

Obviously, the major benefit is that further down the line you can be sure that what you are writing today won’t break what you (or someone else) wrote six months ago. The tests also serve as a type of documentation (why is that method on the invoice class so complicated? let’s simplify - oh, that test fails - it appears you can’t allow the invoice value to be less than £3 on a Wednesday) - especially if you are using RSpec.

But one advantage, that I feel is often overlooked, is because you are starting from the point of view of a user of your code, your method names and parameters are automatically designed from the user’s perspective, not the implementor’s perspective.

One of my favourite examples is

dave.hit nail, :on => :head, :with => hammer.

This makes your method definition look like

def hit target, options  place = options[:on] || :head  object = options[:with]  ...end

In other words the method definition does not reflect how the caller would actually use your method. If you started from the method definition you would probably come up with

def hit target, place, object

end

This makes much more sense from the implementers point of view, but our call becomes

dave.hit nail, :head, hammer

which is slightly less readable from the point of view of someone examining the call in six months time. And those tiny annoyances add up without the reader realising it, till they are tired, the last few lines of code didn’t really sink in and they think fondly back to that other chunk of code that was a joy to read. “Why can’t all code read like that?” they think.

Well, it takes a switch of perspective - one that test-driven development encourages and most other “methodologies” don’t even acknowledge.

This entry was posted on Saturday, September 22nd, 2007 at 6:31 pm and is filed under Beautiful Code, Writing Reliable, Bug-Free Code. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “The advantage of testing first”

  1. Ben Says:

    hear hear - tdd rules, and not just in this new-fangled ruby stuff that all the kids are talking about

Leave a Reply