on TDD (was Re: how to become a really good Python programmer?)

Peter Hansen peter at engcorp.com
Fri Jun 18 20:47:28 EDT 2004


Richie Hindle wrote:

> I think one of the problems I'm having is that I'm thinking like a
> module coder rather than a test coder.  A question for any passing
> TDD-er (not with anyone specific in mind, of course, smart questions
> and all that 8-) - how much does the design of the module and its API
> get influenced by the requirement of writing tests for it?  A coder
> has two tasks: write a module (and the code that needs to use it), and
> write tests for it.  Both will have some bearing on the interface to
> the module, but in what proportion?  My suspicion is that 75% of the
> design of the module's API will fall out of the way the tests are
> written, and that that's a good thing...?

Since I was already here, thought I'd answer anyway... ;-)

I think it depends on the coder and the context (and probably the
phase of the moon) a lot, but sometimes I've found nearly 100%
of the API and design falls out of the tests...  That is, the API
comes from the tests largely, or from when you're writing the tests,
because that's when you are first thinking about "okay, I need
to get an X here, so how would I like to go about getting it?".

The design comes partly from the fact that you have now specified
the external interface, but also from the code you write as you
try to pass the test.  If the tests are small enough (i.e. you
are switching very often between test and code) then the code
will inevitably be fairly modular, loosely coupled, easily
testable, and all or most of those other good things.

And don't forget to refactor... sometimes the design is not
quite so good, even though you are passing the tests, until you
do this critical step.

In other cases, I think I already have a good idea what the API
should look like, probably because "I've written one of these
before".  In that case, the tests may reflect my preconceptions
more.  I wouldn't be surprised if the resulting API and design
are worse in such cases than if I had never written one before...

-Peter



More information about the Python-list mailing list