Good variable naming is context dependent

December 21, 2011

GravatarBy Greg Weber

There were some relatively recent discussions on Reddit about variable naming conventions. In my observations, Haskellers tend to go much to far to the extreme of very brief and succinct names. One reason why is because there are very appropriate times for short and succinct names, such as:

  • generic code
  • standards
  • ease of writing

List code that is truly generic can operate on anything, so using 'x:xs' for variable and 'a' for a type variable is about as specific as we can get. However, if your variable does not represent a generic type, it is very likely 'a' or 'x' is not the best name for it.

There are certain standards, like 'm' for a Monad that would be overly-short names if they weren't standards. One universal programming standard is 'i' for an index. If we didn't follow these short-cut existing standards, we would end up with code that is harder to write, but also possibly code that is harder to read.

Ease of writing code is a subtle point, and has to do with the symbols a library exposes. We must write code keeping in mind 2 points of view - the library author, and the library consumer. The library author must think about what symbols they are asking the library consumer to use. The more frequently a symbol is written, the shorter it should be. The less frequently a symbol is written, the better a more descriptive and longer name is. These concerns should come first before the concern of the library author's own ease of writing their own library. Underneath what the library exports, the library author has a lot more freedom of how to structure their code.

The library author/consumer split manifests itself in many ways. Internally, a library can use whatever types it wants, but it needs to be very concerned about readable error messages for the consumer of the functions it exposes.

One big reason for poorly named (short or otherwise) symbols is because naming is not easy! Calling a variable x, tmp, or a is a way to get it over with quickly. But the only way to get better at naming is to put a little more effort into it - it is a skill I am always trying to improve.

Comments

comments powered by Disqus

Archives