Back when TextMate was relatively new and that famous video of ruby on rails was making the rounds. I watched in amazement with the rest of the nerds as code flew around the screen. I had caught Snippet Fever.

After using TextMate for a while I became addicted to snippets. The basic idea of a snippet is that you can write a few characters and they expand to whatever you want. For example, you can type: ‘fl’, hit Tab and TextMate will write:

  for(int i = 0; i < ... ; i++) {

Where …​ is where the insertion point will be each time you hit tab. You can do the same with Emacs in many different ways: Emacs skeletons, the snippet.el plugging, hand-coded elisp, etc. The point of this post, however, is not to show all the different ways that you can get snippets. The point is to ask whether it’s worth using snippets at all.

Snippets eliminate the need to type recurrent idioms. If you have to write accessors, it’s very pleasant to type ‘set’, hit tab and watch the screen fill with 20 lines of code that just wrap a field in a class with a setter function. But this is fixing the problem in the wrong place.

The fundamental problem is that the language is too damn verbose.

Imagine English had no pronouns so if I wanted to tell you a story about my friend Tim and me, I had to write:

Tim had called Oscar to ask Oscar if Oscar could lend Tim the book that Oscar had bought the day before. Oscar told Tim that Oscar was still reading it, but that Oscar would be happy to lend Tim Oscar’s book when Oscar was done with the book so that Tim could read it.

The above paragraph is too verbose. It’s hard to write. Snippets would help me write it by automatically filling all the appropriate places with “Tim” and “Oscar”.

If the language you are using is so verbose that you need snippets, how about fixing the language?

Even on languages that don’t allow fixing the syntax you can still do something.

For example, in C, if you find yourself typing a for loop to access a list over and over again:

  for (int i = 0; i < length(list); i++) {

Make a small pre-processor macro that abstracts that:

  #define EACH(list) for (int i = 0; i < length(list); i++)

And now you can write:

  EACH(list) printf("%s\n", list[i]);

And since code is usually read many more times than it is written, you have helped make the source base a little better.