Good Variable Naming
2022-06-05
This seems to pop up time and again: What is a good variable name?
if (sigx) { /* ... */ }
if (signal_x_is_set) { /* ... */ }
Both variants have ups and downs, so which is better?
Size Matters, Usefulness Matters More
Short variable names are cool, really, but not if you can’t spot what is meant from the immediate context. Break that rule and you’ll have a hard time remembering what it actually means, what type it is etc. Also you’ll be more prone to naming it differently when the exact same semantic value is used in just a slightly different context a few functions down. See for yourself and check your code from two weeks ago.
The best short names are i, j, k for indices and keys. val for temporary value stores and probably a few more. But before I get criticized over this, let me say that the variable name should not carry beyond the loop or access scope.
int i; // declaration for one or multiple loops
for (i = 0; i < MAX_LEN; ++i) {
// i is my index
if ((i % 42) == 0)
break;
}
// check i one last time immediately(!) after the loop
// e.g. if needed to check if the loop was aborted
if (i == 42) { /* ... */ }
/* ... */
// don't expect i to carry any meaning here and reuse it for the next loop
When the function grows and declarations are not always easy to spot within the file or are even in a different header, it’s much more practical to use a name that’s slightly longer but just descriptive enough: signal_x
, where x is obviously a placeholder. Based on your context you’ll have to judge whether signal_x
or signal_x_is_set
is the better choice. Ask a peer to explain the meaning of the shorter variant. If he gets it right, that’s a good sign it’s good enough.
Use Unit Suffixes
In some languages, some of the units are implicitly standardized: in python time indications such as timeout duration, runtime measurements, timestamps etc. are mostly floats in seconds, such that the unit need not be made explicit when it matches the expectation.
However, when the unit is not clear, it make sense to include that as well: v_mph
. As v is fairly common for velocity in physics, we choose this over “speed” since the unit describes the semantic content. Generally, velocity could just as well be in kph or meters per second and we, thus, add the explicit unit suffix.
Other suffixes we use:
Time: _h
for hours, _s
or _secs
seconds, _ms
for milli-seconds, _ns
for nanosecs
Throughput: _bps
bits per second or _baud
symbols per second, …
Velocity: _kph
kilometers per hour, _mph
, …
Conclusions
There’s no general rule, but putting some thought into proper variable naming will help developers increasing their productivity and overall code-quality.
bitblog