Adam's thoughts on naming in code, tip from Steven about ufcs `i`

Posted 2022-01-31

Core D Development Statistics

In the community

Community announcements

See more at the announce forum.

Adam's random thoughts

Naming seems to be different for three categories:

1) if it is common it doesn't matter what the name is. You know the difference between a battle, bottle, and rattle. But there's no logical design behind those names; they're just common enough words that you learn them through use.

2) it is so rare that if you do ever need it, you're looking it up regardless. You'll be searching for the definition, but the name you'll get from the docs. Your best bet might be making the name just be the definition; at least then readers will have some idea what it does, but they'll probably still want to look it up for full understanding. Not a big problem since you don't need it often anyway.

3) And the third category are the hard ones to do: common enough you use it often... but not often enough to commit an arbitrary thing to memory through rote repetition. These are the ones where you want to focus code review comments.

A useful metric is how local the use is to the definition. If it is a local variable in a small function, for example, you might get away with a more arbitrary name, since you can see exactly what it does for its whole lifetime at a glance. But note some functions have multiple variables or more flow, in which case the fact a variable is local doesn't help that much anymore.

For these, the name should usually be the lesser obvious of what it is and what it does. And I wouldn't worry about length - if you need a few more letters or maybe even a few more words to make it clear, just do it. Typing words can often be done faster than trying to remember what random abbreviation was used last time. (I'm still annoyed with Phobos using currTime instead of currentTime!)

But whatever you do in this category, this is the one to worry about. You'll get used to whatever in common things and won't remember rare ones anyway.

Tip of the Week

Steven Schveighoffer a while ago pointed out that i is almost never a global identifier. Using it for a global identifier works because UFCS is not allowed on locals.

import std.complex;

auto i(double v)
    return complex(0, v);
void main()
    int i = 5;
    auto c = (6 + 2.5.i - 1 + 3.i) / 3.i;

Which is an interesting little tip - the ufcs namespace being a bit separate from other locals gives some potential for cases like this.