Friday, April 16, 2010

In code, a rose by any other name smells less sweet


I regularly get jibed by coworkers for having naming discussions. When my daughter was hanging out at the office the other day and sitting in the back of one of my meetings, she snorted trying not to laugh as we kept going back and forth on how to name something. Just yesterday someone forwarded me Juliet's quote "What's in a name? A rose by any other name would smell as sweet." Very true, very true.

But in code, there is a lot in a name. A different name does not smell as sweet.

The name you give something has a lot of power. In many spiritual traditions, great importance is given to words. Kashmir Shaivism holds that the world is created through the power inherent in syllables and words - matrika shakti. Syllables actually concentrate the universal energy and create form, like vibrations of sound forming shapes in water or grains of sand.



I find this to be particularly true in code. The name you give something gives it a certain power. If you name it well, the role and intent of the class becomes crystal clear. It helps you refine what the class is doing, and strip away what it shouldn't be doing. If it is poorly named, often the code in the class is unclear in its design and role as well.

A great example of fuzzy naming is the famous "Utils" class. You might as well call this class "DumpingGround" because that's what it becomes. Same regularly goes for FooManager, FooHelper, and so on. It doesn't give any real idea what it's for, so it becomes a "whatever" class. Hm, I have a method I want to write, and I don't really know how it fits into the overall design, but hey, here is this Utils class, I'll just use that!

Names also become short-hand for well understood design patterns. If you name something FooBuilder, FooProxy, FooObserver, and so on, then readers expect it to generally follow the pattern. Misusing these well-understood suffixes is asking for trouble.

I often find myself renaming classes over and over again as I work on a piece of code. Each time it helps me refine my understanding. It's like the class and its role in life is slowly taking form out of the primordial ooze, until it stands there clear and strong, with a well-defined shape and purpose.

So laugh and snort all you want, ye plebians. Shakespeare wrote beautiful, beautiful prose, and I am sure he took great care to find the right words. He even invented many words we continue to use to this day. To me writing good, clear code is like the craft of prose - there is a lot to a name, and finding the right name is both an effort and a joy.

No comments: