Hacker News new | ask | show | jobs
by derekp7 2671 days ago
For me this really depends on the context. For example in a small for loop I entirely expect to see the variable "i" used (i = "index" or "iterator"). In three nested loops, I also expect "i", "j", and "k" used for each loop level. This is mostly because it is common enough convention that I don't have to think about it. Same reason I would rather see "2 + 3 * 7", vs "two plus three times seven", the information just gets in my brain faster that way without filler.

Other cases include the comparison function for a sort algorithm, where I expect "l" and "r" for left and right, and the sort function itself I expect to see "a" for array, "c" for comparison function, "s" for swap function.

But when the variables don't really make much sense, or there is no existing convention, then there should at least be a key present for what each variable means.

3 comments

For me it's OK to use i,j,k as loop counters, a and b for sorting algorithms, e for events or exceptions, and x,y,z for coordinates or in simple math operations. Everything beyond that is really out of "everyone is doing it" area, depends on your background, books/people you've been learning from, programming language, etc.
Also, things like X, Y in ML. Explicitly calling this training_data etc will not really aid readers.
Agreed on i, j, k. These really are everywhere.

I feel like your other examples are less obvious though. And I don't see much disadvantage to using full-length names in those circumstances (e.g. left, right, arr, compare, and swap)

I've always used ii, jj and kk, etc. These are just as easy, but allow languages/editors without variable renaming to do a useful search/replace on them, because you just know you will at some point.
Most editors have at least regex search / replace. Most regex flavours allow you to do '\<i\>' or similar to specifiy word boundaries.
Thanks for this tip, would never read it anywhere else and gave a small boost in productivity.