Unit Testing is about Going Faster
Extreme Programming is about taking all the best practices in software
development, and cranking them up as high as they’ll go. Spinal Tap had
amplifiers that went up to 11 – we have XP. Testing is generally agreed
to be a “good thing”, and so with XP we test all the time, by writing
unit tests that exercise every piece of code. Test Driven Development
encourages us to write the tests before the code, thus driving
the design by asking questions about what the code should do – what do
we want to test?
A few nights ago I had a discussion with a colleague about the code
he’d written that day. He was excited and happy because he knew exactly
where he’d wanted to take a piece of code, and had pretty much just
written it straight off. He was concerned, though, that he’d not used
TDD to develop the code. My response was to ask him why he felt that he
needed to use TDD if he was so confident about how he wanted the code
to look.
XP, and therefore Unit Testing, is about delivering working software
quickly. That means you need to be able to write the code quickly,
get it to work (avoid and fix defects) and to be able to change and
maintain the code in future. The fastest way to deliver working software
is to write correct code, straight off, in one sitting, to a known set
of requirements. Most programmers can’t write code that’s perfect, and
most customers change their minds about the features they want (this is
a good thing – we’re embracing change). Your response as a programmer
to the reality of imperfect code is to write unit tests to help check
your work. How many tests you write should depend on how confident
you feel about the code — if it’s similar to something you’ve done in
the past, maybe two or three tests including edge cases will be enough
for you to be happy. Later, if you realise your code had bugs in it,
you’ll learn that you should have written more tests, and take that experience
forwards when coding in future. Similarly, if someone else modifies the
code and breaks it, you’ll learn that you didn’t include enough tests
to make that code maintainable, and do it differently next time.
Proponents of TDD would argue that we’re never sure of the code
to write, or the features we really need (as opposed to those we
think we need). They’d point out that untested code will always
have bugs in it, and will always be broken by future modifications. I
think TDD’s very powerful and use it myself frequently, although not
exclusively. As with any other tool it should be evaluated for the
context in which it’s to be used.
TDD helps you move faster if you’re unsure of what to code, but that
wasn’t the situation faced by my colleague. I’d argue that he should do
enough testing to be comfortable, and still move fast. Finding the right
balance between unit testing and speed of development requires experience,
skill, and good taste.
Posted 12:42, 29 Jan 2004.