API design before implementation (was: Lambda question)

Ben Finney ben+python at benfinney.id.au
Mon Jun 6 19:54:59 EDT 2011


Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:

> On Mon, 06 Jun 2011 12:52:31 -0400, Terry Reedy wrote:
>
> > Let me add something not said much here about designing functions: start
> > with both a clear and succinct definition *and* test cases. (I only
> > started writing tests first a year ago or so.)
>
> For any non-trivial function, I usually start by writing the
> documentation (a docstring and doctests) first. How else do you know
> what the function is supposed to do if you don't have it documented?

By trying to use it. At least, that's my approach: figure out what I
want the function to do by pretending it already exists, and write some
code that expects it to work.

Sometimes that code is a test case (in which case I'm doing test-first
development). Other times I'm not sure what I *want* the function to do
yet, so I'm also experimenting with what the interface should be (in
which case I'm doing something closer to a “spike implementation”).


All of that also stops me from writing the function until I can think of
a descriptive name for the function, and a docstring synopsis: the first
line of the docstring, a self-contained sentence saying what the
function is for. The synopsis should be exactly one short line; see PEP
257.

Once I know the function signature (parameters and return value), then I
write the docstring body.

> By writing the documentation and examples before the code, I often 
> discover that the API I first thought of was rubbish :)

Yep. That's also a big benefit of designing code by pretending it
exists, I find.

Fred Brooks tells us that we should plan from the beginning to throw one
away; because we will, anyhow. You and I seem to have ways to invest as
little as possible in the first design before throwing it away :-)

-- 
 \       “Are you pondering what I'm pondering?” “Umm, I think so, Don |
  `\          Cerebro, but, umm, why would Sophia Loren do a musical?” |
_o__)                                           —_Pinky and The Brain_ |
Ben Finney



More information about the Python-list mailing list