Posts Tagged ‘Coding Standards’

Eye, Aye I!

Friday, November 6th, 2009 Nigel Jones

Today’s post should probably be called ‘Thoughts on non-descriptive variable names’, but once in a while I have to let my creative side out!

Anyway, the motivation for today’s post, is actually Michael Barr’s latest blog posting concerning analysis of the source code for a breathalyzer. Since I do expert witness work, as well as develop products I was keen to see what the experts in this case had to say. One snippet from the expert for the plaintiffs caught my eye. In appendix B of their report, Draeger made the following statement concerning general code issues:

Non descriptive variable names – i, j, dummy and temp

This touched upon something where I seem to be at odds with the conventional wisdom. I’ll illustrate what I mean. Consider initializing an array to zero (I’ll ignore that we could use a library function for this). I would code it like this:

uint8_t buffer[BUFSIZE];
uint8_t i;
for (i = 0; i < BUFSIZE; i++)
 buffer[i] = 0;

This code would be rejected by many coding standards (and apparently would offend Draeger), as the loop variable ‘i’ is not descriptive. To be ‘correct’, I should instead code it like this

uint8_t buffer[BUFSIZE];
uint8_t buffer_index;
for (buffer_index = 0; buffer_index <BUFSIZE; buffer_index++)
 buffer[buffer_index] = 0;

So for me, the question is, does the second approach buy me anything – or indeed cost me anything? Well clearly, this is a matter of opinion. However I’d make the following observations:

  1. I think my code is clear, concise and easily understood by even the most unskilled programmer
  2. Is the variable name ‘buffer_index’ clearer – yes but only to a native English speaker. It’s my experience that there are a lot of non-native English speakers in the industry.
  3. Personally, I find the use of similar words in close proximity (buffer[buffer_index]) to be a bit harder to read, and very easy to mis-read if there are other variables around prefixed with buffer.

I’d also make the observation that many coding standards require variable names to be at least 3 characters long, and as a result I’ve seen code that looks like this:

uint8_t buffer[BUFSIZE];
uint8_t iii;
for (iii = 0; iii < BUFSIZE; iii++)
 buffer[iii] = 0;

Clearly in this case, the person is addressing the letter of the standard (if you’ll pardon the pun), but not the spirit. Where the standard requires the variable names to be meaningful, I’ve also seen this done:

uint8_t buffer[BUFSIZE];
uint8_t idx;
for (idx = 0; idx < BUFSIZE; idx++)
 buffer[idx] = 0;

This code meets the letter of the standard, and arguably the spirit. Is it really any more understandable than my original code? I don’t think so – but I’ll be interested to get your comments.