Tuesday, November 17, 2009

Gratuitous Context

I have been working on code that oscillates between cryptic abbreviations and absurdly long names in functions. Sadly, I cannot reproduce it here for you, or I would. The problems with cryptic abbreviations I have hammered before, so my opinion is well-known (stp bng stngy nd us sm stnkng' vwls, k?). I don't talk enough about gratuitous context.

A name needs to be meaningful in context. The context of a class includes its namespace, the context of a method or class variable includes its class, the context of a method argument includes its method name, and the context of a local variable includes the method that encloses it. This context is cumulative as you navigate namespaces to classes to methods to method inners.

One thing that really is annoying is to see Grouping.Group.MakeGroup(string GroupName) with local variables that all include the prefix "Group". This is gratuitous context. This kind of naming actually hurts the readability of a program.

In a previous article I mentioned three concerns that will affect naming. In this case, we see that a local variable will be close to its point of declaration, and that there are very few variables in play. In this context, all the names are used fairly frequently and never outside of the method. All of these forces drive us to small, easily-recognized names.

Sticking the word "group" on the front of every name not only is unnecessary, it causes the eye to search farther into each word to tell the variables apart. While this is hardly a strenuous effort, it is enough of an effort to cause the reader to exercise extra care in reading instead of taking in the code in a glance.

The contextual prefix also means that the auto-completion of your editor/ide/whatever will pop up a list of names and yours is unlikely to be the first candidate. With a list of similar names, you must exercise additional care to be sure you do not accidentally pick the wrong variable from the list. This is becoming a fairly common type of programming error these days. Usually a pair programming partner will be able to tell that you have picked the wrong variable even if you do not notice it yourself, but this is again wasted effort.

In naming, a long name is not automatically better than a short name. Clarity is the goal. Sometimes longer names are harder to differentiate, which makes them less clear than shorter names, and a long bad name is worse than a short bad name.

For more on this topic, please see Chapter 2 of Clean Code, or the less polished version at my older blog and/or the earlier article the Long and Short of Naming.

1 comment:

  1. I always end up using variable names that err on being to long, hating abbreviations myself.

    but you are right, big names cause clutter, and dont make things distinct.

    id be happy of have the devs on my teams would at least put a tenth of the consideration into naming things that you do