68

I've had a couple of discussions with a co-worker about the use of single letter variable names in certain circumstances inside our codebase, at which we both disagree.

He favours more verbose naming convention for these, and I do not.

There are three scenarios in my opinion where I use single letter variable names:

  • Loops - i for(int i = 0; i < 10; i++) { ... }
  • Lambda expressions in C# - x/y/z: .Where(x => x == 5)
  • Exceptions - e: try { ... } catch(ExceptionType e) { /* usage of 'e' */ }

These are the only scenarios where I would use it, and I obviously use more verbose naming conventions elsewhere.

My colleague put forward the following arguments for exceptions and loops:

  • i - it doesn't mean anything.
  • e - it's the most common letter in the English language. If you wanted to search the solution for exceptions, you'd find lots of undesired instances of e.

I accept these arguments, but have retorts that, if one does not know what i means in a for loop, then they probably shouldn't be a programmer. It's a very common term for loops and exceptions, as is e. I have also mentioned that, if one wanted, they could search for catch in the case of the exception.

I realise that this is subjective, but then, one could argue that coding standards are just that - opinions, albeit opinions by academics.

I would be happy either way, and will forward the results to him, but would rather that we (our company) continue to use a single coding standard, rather than have two developers with different opinions on what to use.

Dan Atkinson
  • 243
  • 1
  • 4
  • 8
  • 21
    Hmm, I always thought `ex` was the idiomatic name for an exception variable. – Cody Gray - on strike Apr 27 '11 at 11:13
  • 3
    I think that it depends more on the scope of the variable than on the usage. There's a lot of overlap between the two. Loop variables for example tend to have a short scope. – Walter Mitty Apr 27 '11 at 11:52
  • 2
    I think that "self explanatory" is more relevant than "verbose". Sometimes a long variable name is needed in order to be self explanatory. Sometimes a one character name can be self explanatory. – Walter Mitty Apr 27 '11 at 11:53
  • 18
    "e - it's the most common letter in the English language" - but it doesn't exist as a stand-alone word. So "searching whole words" in your IDE finds exactly what you need. – eumiro Apr 27 '11 at 11:59
  • 1
    I'd agree with your friend about exceptions, not about iterator/index variables though. In Java, it isn't uncommon to have to handle an exception in an exception handler (i.e. nested try/catch in a catch clause). What do you call the interior exception? I've seen e1, ex, ex1, etc. I typically shorten the exception name, but have it reflect the type of error it is. It just avoids confusion. – Berin Loritsch Apr 27 '11 at 12:06
  • 2
    I use single-letter variables in several other situations: `x`, `y`, `z` for coordinates, for instance, and if I'm computing something using a mathematical formula I'll store the intermediate results in variables that match what's used in the formula. – user13278 Apr 27 '11 at 13:03
  • 1
    The problem is when you end up in a shop like I work and you have nested loops, then naming takes priority. My colleague and I use to go back and forth, he took the site of verbose naming and I took the side of truncation. After working on a few private projects together, I've changed my viewpoint on this; Due primarily because it's easier to read. Try working in a company with nested loops everywhere and your trying to decide what the 'a' index is for, or the 'z'. Personally I name my variables so comments are not necessary that's my rule of thumb. – chrisw Apr 27 '11 at 13:25
  • In addition to all the other examples, I also use `t` for interpolators, or `p` for pixels. When a project has 18,000 lines of code using `p` for a pixel value everywhere, I see absolutely no need to use `pixel_value` instead. – sam hocevar Apr 27 '11 at 16:19
  • 5
    Become a mathematician - that'll solve all your problems. :) – Mateen Ulhaq Apr 27 '11 at 17:07
  • He should have said that `i` by itself looks to much like `l` and `1`. After about the 20th time of debugging to find it was an error between those three I stopped using `i` and `l`. – Hogan Apr 27 '11 at 17:27
  • 11
    I prefer `ex` for exceptions and `e` for event arguments. – Peter Olson Apr 27 '11 at 22:23
  • 1
    **Commenters**: comments are not meant to be used for extended discussion, but for clarifying the question. Please use [chat](http://chat.stackexchange.com/) for discussion, not answers. If you want to express your support for a standard, see if any of the existing 20 answers list it and upvote that answer. If there's no answer that fits your view, add one. – Adam Lear Apr 29 '11 at 13:49
  • 1
    I don't want to write a new answer to this old question, and this is just a comment. There's a key concept missing from the list of places where a single character variable name is acceptable, and maybe even preferable, and that's C++ templates. It's very common to see something along the lines of `template ...`. – David Hammen Jun 02 '14 at 15:47
  • 1
    @gnat - Given that this question is older, I'm inclined to say that the other issue is a duplicate. :) – Dan Atkinson May 30 '15 at 19:20
  • "i - it doesn't mean anything.", but it make sense, which any one understands that 'i' is for 'index' or 'iteration'. This how all programmers write their first for loop (and forever :)) which is a well-known convention. I would say if it was something like 'a' it does'not make sense. – Dhanuka777 May 18 '17 at 02:00
  • They're also used in python contexts also for lambda expressions but likewise for list-comps and genexp's. In fact the original list-comp [PEP](https://www.python.org/dev/peps/pep-0202/) uses `f` for `fruit`, which is also a single letter convention where the first character is used to abbreviate with. – jxramos Oct 11 '19 at 20:37
  • I second the observation by @chrisw about nested loops. I worked on projects that would span the three spatial dimensions frequently x,y, and z for entities with different contexts. Suggestive index names helped a lot here and actually made the code less bug prone for easy to make copy paste errors mixing incorrect indexes. For nestings 3+ deep I'd say its essential to drop the single character convention. – jxramos Oct 11 '19 at 21:09

20 Answers20

84

I entirely agree with your opinion, and believe it isn't all that subjective.

The name of a variable is only as relevant as its scope.

There is no point in endless discussions about a name of a variable which will only be read by a person reading that particular small scoped piece of code. On the other hand, class names and member names need to clearly indicate what is going on. A lot of the expected behavior needs to be explained in a concise name.

Conventions improve readability.

i and e are common conventions used for those small scoped variables. Their intent is really clear if you know the convention.

Conciseness improves readability.

A short variable name which represents its intent clearly is to be preferred over a big variable name.

Steven Jeuris
  • 5,804
  • 1
  • 30
  • 52
  • 33
    To your last point, the shortness of the variable is part of the communication of intent. If I use `i`, that communicates that this is a transient, unimportant index. If I use `index` that suggests this index is slightly more substantial, but less important than `accountIndex`, etc. – Eric Wilson Apr 27 '11 at 15:19
  • I totally agree with you, except on the OP's second point. Lambdas in C# often get looked upon as black magic, and descriptive names help with that substantially. – Magus Mar 31 '14 at 21:03
  • Any generally-agreed convention for situations with *multiple* index variables? `i, j, k`, for example? or `i, ii, iii`? – CosmicGiant Jun 19 '18 at 23:57
  • 1
    Agreed, the _shortness_ is indeed a valid avenue for communication, being directly proportional to scope/lifetime-extent/ephemeralness. It is quite suggestive indeed for it adds an intentional degree of anonymity for what is really only a “syntactic [background actor](https://en.wikipedia.org/wiki/Extra_(acting))” to make an analogy to casting in performance arts. – jxramos Oct 11 '19 at 21:02
  • To carry this casting analogy further as a writer you have to give proper focus to the main characters and in descending order to supporting characters, [bit parts](https://en.wikipedia.org/wiki/Bit_part), and the least to _background actors/extras_. That's why we see things like "Boy #2, Girl #3, male plumber, etc" in movie credits. These characters go nameless in the production, and are only identifiable at the credits due to their brief roles that even warrant or contain some identifiable mention. In code the most minimal identifier representation is through the single character. – jxramos Oct 11 '19 at 21:02
54

This really depends on the situation/context (and there is no one fits all solution).

In general i,j,k [btw, i can be taken as index; its usage comes from mathematical background where those were most often the first three indexes (remember tensor calculus). It may also be connected to Fortran's history, where i being the first implicitly typed integer, was often used as an index of a loop. ] are often used if it is a simple counter. If it has a specific meaning, like month or year then longer variable name is better.

Rook
  • 19,861
  • 9
  • 53
  • 96
  • I agree with you and I want to add that although index is more meaningful it is a reserved word in some languages so we simply use i. – M.Sameer Apr 27 '11 at 11:26
  • `i` can also be thought of as "iteration". – hippietrail Apr 27 '11 at 12:57
  • 2
    @M. Sameer - You misundestood. I didn't mean to say "i" should be replaced by "index" for convenience, but that "i" means/can be taken as an index (of a loop). Not in the way that you should go and rename "i" to "index" however. Perhaps this is an english language thing, and I'm missing some finer aspects of it. – Rook Apr 27 '11 at 13:16
  • @Rook: maybe replace **i** the letter with `i` the variable name for clarity? – sam hocevar Apr 27 '11 at 16:21
  • @Muffun - Rollback of an edit that was made without any explanation as of why, that does not contribute to the point, etc. etc. – Rook Apr 27 '11 at 16:21
  • @Sam Hocevar - Please do. I'm still sometimes struggling with the marking language here. – Rook Apr 27 '11 at 16:22
  • I typically use index rather then i, but that's only to try and force myself not to be lazy when deciding when something else besides i(ndex) makes the most sense. – Winston Ewert Apr 27 '11 at 21:37
  • @PéterTörök +1 for +1 for pointing out the math background. – August Karlstrom Jan 22 '14 at 14:36
24

I agree with you: i as a loop variable name is an age-old idiom which should not confuse anyone. Same as e for an exception variable in a catch block. The latter (or rather both) should be short and simple, making the scope of the variable small, limiting the possibility of confusion for readers. And if someone wants to search for exceptions, better search for exception types or catch blocks anyway.

This said, I personally prefer using longer loop variable names such as index or idx. My reason is that i is so short, it is difficult to locate with the cursor.

Update

For reference, your coworker's arguments probably come from Ottinger's Rules for Naming - an excellent and pragmatic approach to the subject, recommended for reading. However, he may have overlooked the parts quoted below:

My personal preference is that single-letter names can ONLY be used as local variables inside short methods. The length of a name should somehow correspond to the size of its scope. If a variable or constant might be seen or used in multiple places in a body of code it is imperative to give it a search-friendly name.

And

Certainly a loop counter may be named i or j or k (though never l!) if its scope is very, very small and no other names can conflict with it. These are allowable because those are traditional solution-domain names.

Péter Török
  • 46,427
  • 16
  • 160
  • 185
16

I prefer meaningful variable names, even for loop variables. So, I usually write something like

for (int vertexIndex=0; vertexIndex<polygon.VertexCount; vertexIndex++)
   DoSomethingWithVertex(polygon[vertexIndex]);

I realize that there's little difference (either way) for a small loop like this, but:

  • if the loop body is longer, vertexIndex is often clearer than i. Of course i is an index, but what index? To which array? To which element in that array?
  • if the loop body calls other functions and passes the index as an argument, it's often easier to name the value consistently at the caller and the callee locations - and you wouldn't want to call method parameters i and x
  • if there are nested loops, using i, j, k as indices is very confusing and error-prone

to be consistent, I just use meaningful variable names for loop indices everywhere.

@André Paramés asked: "If the loop body is long enough to hide the meaning of i, isn't it time to refactor?"

A typical human brain has a short-term memory capacity of about 7 chunks of data. So if the loop body contains 8 or more chunks (where "chunks" are statements, local variables, parameters, comments), then your brain can't store the meaning of each of those chunks simultaneously. Instead, your brain will shift chunks in and out of the working memory while you read the code. For example, if you use variable names like i and j your brain will shift the meanings of i and j out of its working memory; the next time you read j, your brain will usually rely on context to find the meaning i.e. if you read customers[j] in the middle of the loop body, your brain will infer that j is an index into the customers array. If you had written customers[vertexIndex], you would see that you're using the wrong index. And that's for very short loop bodies with only 8 chunks of information, i.e. 5-8 lines of code.

If the body gets longer, you would typically extract it into a separate function with a parameter vertexIndex. And that's the second point I was making: If the variable is named vertexIndex inside that function, it should really be called vertexIndex at the caller, too.

nikie
  • 6,303
  • 4
  • 36
  • 39
  • 5
    If I had to work with you, we'd have a religious war/Jihad. – Omega Centauri Apr 28 '11 at 03:36
  • 1
    If the loop body is long enough to hide the meaning of `i`, isn't it time to refactor? – André Paramés Apr 28 '11 at 11:25
  • 3
    +1 for nested loops. Simple variable names can improve the readability of a nested loop. For example, when iterating through a 2D array or a table, labeling the variables `row` and `column` can be more readable than `i` and `j`. – Steven Apr 28 '11 at 20:48
  • to me `myArray[i]` is way more readable than `myArray[myIndexArrayDescribingSomethingTooLong]` – Rémi Dec 22 '14 at 14:50
  • 1
    @im_a_noob: Then you probably never had to debug somebody else's code that was littered with expressions like `myArray[i][j]` and `myArray[j][i]` (which one's the right one? `i` was the employee index and `j` the project index, right? Or was that the loop above?), or my favorite: `myArray[l][I][1]` (no, they're not all three the same character). Code like that probably started its life as a 1d-array with one loop variable, but it didn't stay that way... – nikie Dec 22 '14 at 15:17
  • @nikie well of course nothing is all black or white. What I'm saying is that in most case it is more readable (for me) to have 1 letter name for those variable. Btw if someone process a 3d array in one method there are probably some stuff that could be refactored. – Rémi Dec 22 '14 at 15:35
15

more verbose names can be just as meaningless. "i" is so commonly used as a simple iteration counter, it's almost standard practice. Calling the same counter "iter" because some "coding standard" prohibits single letter variable names doesn't add any value whatsoever.

"x", "y", and "z" are standard coordinate names, calling them xCoord, yCoord, zCoord adds nothing.

"e" of course is a mathematical expression. But it's relatively common to use it as a name for exceptions in catch blocks in Java. Calling it "exc" or something similar wouldn't again add real value.

jwenting
  • 9,783
  • 3
  • 28
  • 45
  • 1
    Thanks for your answer. Regarding x/y/z, this seems to have been the common usage for lambda in C# since its exception, and I've just gone with the community on it. In this case though x/y/z aren't related to coordinates, but are checking instances. So in C# `.Where(x => x == 5)` would be similar to a for loop statement `if(i == 5)` or `if(myArray[i] == 5)`. – Dan Atkinson Apr 27 '11 at 10:37
  • 1
    Also event args are usually called `e`. Probably because its common practice to append `EventArgs` to the end of the parameter type name. – Nobody Apr 27 '11 at 10:38
  • I doubt Dan's coworker argued for adding useless noise characters like "iter" instead of "i" or "xCoord" instead of "x". Nobody would name their variables like that, except people who deliberately try to follow the letters of coding standards, but not their spirit. – nikie Apr 27 '11 at 10:50
  • I've done it, when running out of meaningful names to use when having to work under such rules, and I think most of us have experienced things like it :) – jwenting Apr 27 '11 at 11:12
  • @nikie Well, propose a more meaningful name for coordinates then. – Konrad Rudolph Apr 27 '11 at 15:01
  • @Konrad Rudolph: To propose a more meaningful name, you have to know more about the meaning of the variable. Anything else is useless verbosity, that's my point. You'd have to know what these coordinates designate - e.g. if it's the position of the center of gravity, then `xCenterOfGravity`/`yCenterOfGravity` would be candidates. If the coordinates really don't *have* a meaning (as e.g. the `X`/`Y` members of a `Point` structure) then `X`/`Y` is fine. But in my experience that's the exception, not the rule. – nikie Apr 27 '11 at 15:25
  • @nikie What information does “CenterOfGravity” impart then, *in the context of a center of gravity*? Exactly none, is my point. The only *distinguishing* information, and hence the only relevant information, is conferred by the coordinate names proper, `x`, `y` and `z`. If you really need to differentiate between different sets of coordinates, you better use appropriate structures, i.e. you have `CenterOfGravity.x` etc. Either way, the general use-case is always best expressed by an appropriate type, not the variable name proper. – Konrad Rudolph Apr 28 '11 at 00:07
10

I don't agree with your colleagues points.

To me, i means "iteration". Quite meaningful in the case of a loop.

Most IDE's allow for regex-type searching through the text. So you could search for 'e' not inside a word. That would be effective.

TZHX
  • 5,052
  • 2
  • 25
  • 32
  • 1
    Hell you could pretty much just search for " e)" and find a particular instance. –  Apr 27 '11 at 10:30
  • 12
    You could just look for the `catch` keyword, because that's where you find all those `e`s. Which makes a lot more sense than having to rely on a naming convention. – user281377 Apr 27 '11 at 11:10
  • 3
    Or you simply search for the exception type, because usually you don't really care about (or want to find) *general* thrown exceptions, do you? At least when I search for an exception I do it because it was thrown, and shown in the stack trace, in which case I usually have both the type and even line numbers. – poke Apr 27 '11 at 16:59
  • No regex needed if you have visual studio, under find options check "Whole Word" – Mark Lalor Apr 29 '11 at 23:14
6

Short variable names are like pronouns in natural languages: to be used in a small context/scope. "i" in a short loop (no nestings) or "e" in a sequence of a few catches are perfectly ok. In many cases the long/descriptive name for "i" would be "the_stupid_index_needed_to_get_at_the_really_interesting_things" and you use a lambda expression just because it is needed in one context only.

Perl's $_ is a super-pronoun that works (for Perl programmers); though being allowed/encouraged to skip even 'it' (just "print" to "print $_") is something I'm a bit afraid of.

Searching for variable names to spot problems in code would not be my first idea. I think the programmer should have an idea about the class or function where to look in case of specific trouble.

Ekkehard.Horner
  • 221
  • 1
  • 4
  • I really like your analogy to pronouns. Also some fields have importanat quantities with simple names, and lots of literature using them in a standard way. For instance if you are solving for light intesity problems then I(angle) is the intensity of light at a given angle, and the clode is clearest if that is what you use. The ickyest thing is to have to figure out what a messy algebraic expression means when all the variables are twenty or thirty characters long). I'm sorry my brain can't fathon algebra with long variable names, but has no trouble with short ones. – Omega Centauri Apr 28 '11 at 03:34
6

(This is .NET-centric but your question mentioned C# lambda expressions, so I think this is relevant in your case.)

I would always use ex for an exception, as e is already used (by WinForms and ASP.NET WebForms conventions) as the EventArgs-typed argument for an event handler.

e.g.

protected void button_Click(object sender, System.EventArgs e)
{
    try
    {
        // whatever
    }
    catch (Exception ex)
    {
        // some exception handling
    }
}

However, MSDN uses e for exception variables.

During this discussion I'd suggest keeping two things in mind:

  • Variable naming conventions can usually be considered a form of religious war.
  • The most important coding convention is to keep to the style of the existing code.
Richard Ev
  • 211
  • 1
  • 2
  • 8
  • 1
    Yes, this is a good point. I'd say ex is also valid, and my colleague and I have discussed EventArgs as somewhere where the convention would need to change. However, we use .NET MVC so do not encounter this. Also, `EventArgs e` is done automatically by the VS IDE, which suggests that Microsoft also favour single letter variable naming in some circumstances, rather than `eventArguments`... – Dan Atkinson Apr 27 '11 at 12:32
5

I don't see any question here, but "i", "j" usually refer to coordinates just like "x" and "y" (my personal preference), I understand "e" might be a too common, but if your searching for exceptions, jus to that search "Exception".

the biggest problem of using single letter variables is that you might get confused with them, but if that variable has a limited scope, like in a loop or in a try catch , I don't see any problem with it

IvoC
  • 129
  • 3
  • The question was 'what is the opinion of the community on this discussion'. Although the lack of a question mark doesn't necessarily mean lack of a question. :) – Dan Atkinson Apr 27 '11 at 11:58
5

It is usually not very relevant when you have a single loop, and I prefer to use i or j for simplicity (and because of the convention). With nested loop, I sometimes use more verbose names to recognize which index relates to what. For example, if I have two arrays: of dates and quantitites, and I have a nested loop iterating first over dates, and then over quantities, I would use names dateIdx and quantityIdx, to prevent confusion. I've had bugs in my code when I wrote

matrix[i][j] = fun(dates[i], quantities[j]);

but should have

matrix[i][j] = fun(dates[j], quantities[i]);

With more verbose names, I would easily spot the error, as

matrix[quantityIdx][dateIdx] = fun(dates[quantityIdx], quantities[dateIdx]);

would just look wrong.

quant_dev
  • 5,117
  • 2
  • 22
  • 26
  • I think your example is just biased to support your argument. `matrix[dateIdx][quantityIdx] = fun(dates[dateIdx], quantities[quantityIdx]);` would not look wrong at first sight either. – sam hocevar Apr 27 '11 at 16:17
  • 1
    So instead of 2 places where a mistake can occur, you have just one. A 50% gain. – quant_dev Apr 27 '11 at 16:35
4

An interesting epistemological question is that of meaning. Your colleague seems to assume that just because something means something to him, then there is meaning and otherwise it isn't.

The truth is, of course, that all those symbols we are using everyday, not just in programming, have meaning only because we attribute it to them. Or, to put it differently, the meaning is in your brain, not in the symbol. (To make this clear to oneselve, think of a cuneiform tablet - surely it did have meaning to the writers once upon a time, yet to most of the billions of people today it has not.)

In the light of this, the assumption that long names mean something, while short names do not, is absurd. Moreover, the expectation that a long name in a program text somehow carries the meaning it possibly has in a different context can lead to confusion.

Ingo
  • 3,903
  • 18
  • 23
  • Length is not the issue here. You could refer to someone by their full name (e.g. Joanne Rowling) and make it more confusing. You would not use the abbrev. 'auth' in a B app and exp. it to carry-over to a NASDAQ app. – JeffO Apr 27 '11 at 11:50
4

A few points:

  • I've heard it suggested that you should prefer to use "ii" to "i" because if you ever do have to search for your loop index you'll be able to do so (and it's more visually distinct in general), and I think that's a good idea.
  • It depends on the scope and content of your loop. If your loop is simply doing something 10 times (eg. if it doesn't even access the loop variable at all), then I think "i" or "ii" is a thousand times more reasonable than a longer name. Everyone who has ever programmed at all should know or learn than "i" normally means "loop variable"
  • If your loop has a large-ish block of code inside, consider extracing that to a function, but either way, it may be valuable to have a short but meaningful name, eg. carIdx or day, not least because you may want to use "i" within the body of the loop.
  • If your loop is looping over the contents of a data structure, use a relevant name: an abbreviation or lowercase form of the datatype or variable contained if it's reasonably distinctive (eg.foreach car in carsOwned), or a longer form if your loop is more complex.
  • I think the same applies to lambdas and exceptions, although I'm less familiar. For instance, if there IS a sensible name for the input to your lambda, especially if there's more than one, then use it, but most of the time, the whole POINT of a lambda is to take an anonymous input, which everyone understands "x" to mean very well.
Jack V.
  • 1,120
  • 7
  • 6
  • Eeeew... out of curiosity why would you ever need to search for a loop index, a loop is a completely standard construct and no matter what you call 'i' you are going to locate, at a minimum, all the loops in your project. – Chris Nicola Apr 27 '11 at 20:13
  • Chris: Well, uh, I was thinking more like "I changed this loop to count down rather than up and want to find all places in the function where the loop variable is used and make sure the change doesn't affect any of them" rather than "the concept of looping is changed and I want to change every single loop in my whole program, except those where I used a different loop variable". – Jack V. Apr 28 '11 at 10:19
  • 1
    If your loop takes up more than a dozen lines, it's likely it needs refactoring. Even with long loops I don't think I've ever had a problem finding all references to `i`. Plus if it's an array index you can normally search for `[i]` if you must. – DisgruntledGoat Apr 28 '11 at 14:50
4

When talking about readable code, you have a few things to consider:

  • What are your coding standards?
  • What are common conventions for your platform?
  • Is there the potential for confusion?

Assuming your coding standards do not say much about variable naming conventions, should think about discussing the code. For example with the loop below:

for(int i = 0; i < 10; i++)
{
    function(i);
}

The loop and all its functions can clearly be seen for the entirety of its scope. Now, imagine if we have nested loops (my favorite is the loop within a loop within a loop); or perhaps a loop that spans 100 lines. At that point, single letter iterators don't make a lot of sense, because it's so easy to get lost in the scope. You might want to refactor that 100 lines of code into some methods/functions to tame it a bit, but give the index a meaningful name.

On the subject of exceptions, I'd tend to agree that e just isn't a good name. However, my reasons are different from your friend's. I've done a lot of Java programming over the years, and have to deal with all those nasty checked exceptions that will never get thrown unless someone hacks your Java install. It's a fact of life. So as you are handling an exception, you have to encapsulate part of your exception handling within another exception handler. A common place this occurs is with JDBC code.

Bottom line, since each exception you were checking needs a unique name, and you are handling several types of errors in one try clause, give those exceptions names that mean something. Seeing e, e1, e2 doesn't help when I'm reading the code. What type of exception am I looking at? So again, since there is room for confusion, use long names.

Berin Loritsch
  • 45,784
  • 7
  • 87
  • 160
  • on the subject of the loops within loops, using conventional variable names would not necessarily be a problem and may even be an advantage: if you see a `i` you know its the iterator of the outer loop, if you see a `j` you know its the iterator of first nested loop and so on... That being put, it still is a case by case decision. – João Portela Apr 27 '11 at 18:24
  • That's why I provided the three questions to ask yourself. It helps work through if the variable name will help/hurt/or is inconsequential. – Berin Loritsch Apr 29 '11 at 13:09
  • I agree that you should always ask those questions. But, in the example you provide you say: "At that point, single letter iterators don't make a lot of sense, because it's so easy to get lost in the scope." and I was trying to show a different (and also valid?) point of view for that same example. – João Portela May 02 '11 at 17:01
  • @João Portela, I agree that `i`, and `j` are commonly used for nested loops (essentially following the alphabet so a third nested loop would use `k`). Assuming there is no confusion, there's nothing wrong with following convention. I'm just not a fan of that convention because in some fonts there isn't enough distinction between `i` and `j`. That's more a problem for proportional fonts which are not typically used for programming, but it's still a potential source of confusion. Having had to use one such font to edit a file, the only difference between i and j was the length of the tail. – Berin Loritsch May 02 '11 at 17:09
3

I use i as a counter in loops only when:

  • it is used as an index; and
  • when its scope is very short.

As Rook said, the term i has a mathematical background as an index which tagged along as a programming convention. However, if it is a long loop, containing many variables, I would rename the counter i to something more explicit. If you have nested loops which iterate over for instance a matrix, I usually use row and col instead as i and j aren't exactly clear of what they refer to anymore ("Was it A[i][j] or A[j][i]...?").

Concerning e for exceptions I tend to use ex because I've seen e be used for element.

gablin
  • 17,377
  • 22
  • 89
  • 138
2

It comes down to the difference between "What are you doing?" vs. "How are you doing it?"

First of all, where possible, use a foreach rather than a for. It better expresses what you are doing (i.e. Walk through the collection, and process each element.) This eliminates the problem of naming altogether.

If the index variable has any meaning at all other than "the_stupid_index_needed_to_get_at_the_really_interesting_things" (thanks E.H.) then use that meaning. row and col should be preferred over i and j if the array is representing a table. I also like to use position or pos if I'm doing lots of swapping.

However, the for (int i = 0 ....) idiom is so well established, that it is the de facto standard for an iteration. Don't mess with well established idiom without good reason.

Exception to above: Math or Physics -- Use the standard formulae from the text.

v = d/t; is more familiar to a physicist or engineer than velocity = distance / time;

Chris Cudmore
  • 553
  • 4
  • 13
1

Although I have no problem using "i" , conding standards demand something more. I wouldn't waste time arguing if it is necessary. For me "loopIndex" and "loopCounter" are two standard names I use instead of "i".

DPD
  • 3,527
  • 2
  • 16
  • 22
1

@nikie listed some of my arguments already, but I want to add that your argument for limiting verbosity is weak.

Looking at the code in isolation, a more descriptive name would help. Identifying the loop itself is not an issue like you mentioned.

You will be using the 'i' many times in an app and could save some typing, but they don't all refer to the same thing. Many SQL scripts will alias a table with a single letter, but every time it is used, it's referring to the same table.

Coming up with meaningful names can be difficult, which is why it is best to make it a habit.

JeffO
  • 36,816
  • 2
  • 57
  • 124
  • The *meaning* of a name in a program is quite exactly determined by the programming language used. Hence, there is no such thing as a more or less menaingful name. Your point here is to *suggest* certain meaningings to human readers. – Ingo Apr 27 '11 at 12:17
  • @Ingo - "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." ~Martin Fowler – JeffO Apr 27 '11 at 13:04
  • 1
    Thats the point in question: should a *programmer* understand a loop variable called *i*? Yes, indeed! It makes absolutely no sense to make it supposedly "easier" for him by naming it variableThatWillBeIncrementedBeforeEachLoop. – Ingo Apr 28 '11 at 08:33
1

For "e", which of course stands for "exception" or "error", it's easy to search for exceptions, you just have to make sure that your search matches whole words (could also search for "e)" with matching whole words, if you don't use a space between the variable and the parenthesis), you won't find many "e"s all by themselves, except in the exception handlers.

For "i", it does have a meaning: it stands for "iterator" (or possibly "index", or "incrementor").

There is another reason to have a short variable name: shortcuts to what would be longer variable/class names which are used very often in a framework or what have you. Such as the JQuery "$".

Phoenix
  • 131
  • 4
1

I thought i stood for 'increment'. I think the large number of different answers indicates there is something to the original question about meaningfulness of variable names--they often mean something traditional, but many people use them without knowing what the tradition is. It's easy to say that someone who doesn't know what i stands for "shouldn't be a programmer", but how do you learn what i stands for? There are a half-dozen answers right here.

David Rhoden
  • 101
  • 3
  • The variable used in for loops is called the "iterator," not the "index" or "increment." Although the iterator, i, is often used to reference an index within an array, that is not necessarily the case. It might be used to facilitate asking for a number of pieces of input from the user, do thousands of other things, or simply be a dummy variable that isn't used at all. An index, on the other hand, has a more strict definition: it's the offset, from an array's base memory location, of a specific piece of data, i.e. int itemVal=[array[0]+(index * sizeof(int)] – Michael Apr 28 '11 at 10:35
1

Steve McConnell in Code Complete had great advice for verboseness of variable names, it all depends on the scope and use of the variable. If you have a large class, your member variables better have clear names as you want to know what the variable represents when you're buried in code half way down the file. If you have a short function or a variable only used for a few lines of code you can make as short as you want as you aren't going to get confused about where its defined or what it represents, and a smaller name makes the code clearer.

Therefore for your case, i, e and x are great variable names. (assuming of course you dont have big complex loops)

Richard
  • 398
  • 2
  • 5