An example is worth 1000 words

One of the tricks I use when I first start writing a chunk of code is to package the code up in a namespace, and I (almost) always include a working example as part of the implementation. I have found that this can be both a timesaver during development and also a year or two later when I've forgotten how the code works and want to use it again in a new project.

This past weekend I was cleaning out some of my directories and came across some old code I hadn't touched in a couple of years. One file was called "wrap.tcl", which I vaguely recall was used to add a binding to text widgets that would intelligently wrap the current paragraph to a particular column width. This code wasn't in a library of a released project but rather in a personal "hacks" directory that I tend to leave in my wake. Was this working code? Did it do what I was guessing it did? How do I use it?

The first thing I did was to open the file with emacs and look at the end of the file. There I found the following block of code:

proc ::wrap::example {} {
    catch {destroy .t}
    pack [text .t -wrap none]
    bind .t  <Control-space> [list ::wrap::wrap %W insert]
    .t insert end "To cause the text in this
paragraph to wrap, place the cursor anywhere in 
the paragraph then press control-space.

* notice how it also will
intelligently wrap bulleted paragraphs
* yada yada
yada"
}

I instantly knew the basic feature of this chunk of code and also had a way to immediately test it out. Of course, if I had written sufficient API documentation maybe I wouldn't need this crutch. However, we all know that in the real world documentation is just about the last thing that gets created, and the last thing to get updated when the code changes. This is perhaps doubly true for code that isn't part of an official project but instead is just something that gets created out of idle curiosity or to solve an immediate need.

Because I had taken the time a couple years ago to write this short example, in just one minute, if that, I was able to determine:

  1. what the code did
  2. how to use the code
  3. whether the code actually worked

That's a lot of knowledge to be gained about the code in a file, from just a baker's dozen lines of code.

Including a working example right in the implementation itself doesn't make the documentation problem go away but it does make it easier to keep the example in sync with the code and provide at least a modicum of factual documentation.

Practical advice

If you're just starting out as a Tcl programmer, I recommend learning about namespaces so that you can encapsulate your functionality in reusable units. Once you get past that hurdle, adding an example proc to your files as a matter of course can help make your code more easily reusable over the long run.