3 ms·
Index isn’t going to be consistent when you need a second iterator in a generic algorithm; people just don’t like the sound of jndex. Use “i” and “j” and “k”, o
by seanmcdirmid 8y ago
Index isn’t going to be consistent when you need a second iterator in a generic algorithm; people just don’t like the sound of jndex. Use “i” and “j” and “k”, or “idx” and “jdx” and “kdx” if you must, but please don’t use “index1” and “index2” and “index3.”
As you say, list might be the best name for a variable if the use context is generic. The same with iterators and such. But you really have to think ahead to keep the names consistent, complicated names work against consistency.
- deleted 8y ago[deleted]
- jdmichal 8y agoWell, if you combine the two together... List<Foo> foos; for (fooIndex = 0; fooIndex < foos.length; ++fooIndex) { Foo foo = foos[fooIndex]; List<Bar> bars = foo.bars; for (barIndex = 0; barIndex < bars.length; ++barIndex) { Bar bar = bars[barIndex]; } } It would be immediately, visibly obvious if you accidently use `fooIndex` in the `bars` list. Good luck getting that with `i` and `j`. That, of course, is assuming you even need the indexes. Otherwise you get this: foreach (Foo foo in foos) { foreach (Bar bar in foo.bars) { } }
- Jtsummers 8y agoYou have more context (in that first example) and so the foo and bar indexes make great sense. i and j really make more sense (as i and j) when used in their more mathematical connotation: indexes into a multidimensional array/object. for (i = 0; i < thing.length; i++) { for (j = 0; j < thing[i].length; j++) { thing[i][j]; // this is very close to the mathematical use of indexes } } Makes perfect sense because i and j are being used to index into the same thing. i and j would be poor fits for your first example because they don't index into the same thing anymore. You've introduced additional levels of indirection, to rewrite your first example using i and j (and illustrate why this is an awkward construct): for (i = 0; i < foos.length; i++) { for(j = 0; j < foos[i].bars.length; j++) { foos[i].bars[j]; } } It's not wrong, but it is awkward and unclear as the code grows larger it becomes easier to misuse i, j, and subsequent index variables. ===== And of course, you're absolutely correct: foreach or equivalent is a better construct. It states the intent of the code, rather than the how of the code. This keeps your code closer to the semantics of your problem specification.
- domenukk 8y agohowever I would skip j as it is too similar to i. Use k instead.