views:

791

answers:

15

I notice, in C# i use very short variable names EVERYWHERE. My code is polluted with

foreach(var (v|f|i) in SOMETHING)

for(int (i|n|z)=0

var (ret|r) = blah();
...
return ret;

var sw = new StringWriter();

using(var r = cmd.ExecuteNonQuery()) {
    while(r.Read()) {
        r.GetSomething(3)

I dont know if this is bad or ok. I can certainly read it. I havent looked at code 5months ago or older so i cant say if i understand old code. All my functions are short and do one thing so by reading the function you can get a good idea what the variable is, especially since theres <=5vars in a function.

People use to yell at me about not using good variable names. Am i not using good variable names or is this ok?

+15  A: 

Unless your code is minified, you shouldn't see vars like this all over the place. Your code should be effortlessly intelligible.

I recall hearing that we ought all code as if the next person to manage our project is a psychopathic killer who knows where you live.

Jonathan Sampson
Re your second paragraph, the traditional formulation also includes the phrase "who knows where you live." (Kidding aside: one wants to pre-empt the response of, "Yeah, but what do I care, I'll be gone by then.")
itowlson
+1  A: 

I might not know what 'r' is later on in the code. Also, variable names are one thing, but you should be commenting code for the verbose explanation. NB: This should probably be a community wiki as there's no definite answer.

keyboardP
I think there _is_ a definite answer. As with the issue of shape of the the Earth, there will be some people thinking it to be flat, but on the whole there will be agreement...
mjv
That's a fair comment. I guess I meant from an objective point but, as you say, there probably is a consensus on this.
keyboardP
+2  A: 

I have no idea how you can keep track of things when you have variable names like that.

Generally, its much better to have longer names that actually describe the variables. The thing to strive for is for anyone to be able to read the code and understand whats going on, to be able to understand what they are for etc =)

Ted
like i said, <= 5 of them =). Most of my func are < 20 lines.
acidzombie24
+4  A: 

It's not just a matter of good variable names (which is a good idea) but rather if someone else could make sense of what you've written relying on the comments as well as the variable names.

Sure, for things like counters or simple actions short and concise names make sense. For more complex algorithms or something that is a little harder to read, you'll want to elaborate to the extent that the code is clear.

Every shop and every developer is different. At the end of the day, try to write your code with consideration for the next guy that might have to maintain it.

Mat Nadrofsky
+4  A: 

Using one letter variable names as indexes in loops or in short well defined blocks is normally considered ok. However, there is nothing wrong with using descriptive camel case names that convey meaning to others reading your code, for things like function arguments and local variables.

+4  A: 

With limited exceptions, no - this is not OK. There's just no excuse any longer for single letter or overly abbreviated variable names. Even if you're a hunt-and-peck typist, intellisense means you almost never have to spell anything out. If you continue to name variables this way you are punishing both yourself any anyone unfortunate enough to be tasked with maintaining your code.

Jon B
really? So fluent style code where the varible names are so short they don't exist is not allowed?
Scott Weinstein
for(i = 0; i < 10; i++ ){printf("I agree.");}
Robert
+14  A: 

Using short variable names for local variables is okay as long as the scope is limited.

Personally, I find that for simple usage short concise variable names tend to be easier to read than longer ones.

using (StreamReader sr = new StreamReader(inputStream))
{
    sr.ReadByte();
} 

As opposed to:

using (StreamReader streamReader = new StreamReader(inputStream))
{
    streamReader.ReadByte();
} 

It's really all about readability. Every situation is different, and developer teams are different. Follow the coding standard for the project, if that exists. If not, follow the style of existing codebase, if that exists.

I agree with some of the answers here say that variables names should have good names. But I believe that presupposes that an object has semantic value. Sometimes, it doesn't. In some cases, you just need an instance of a specific object to perform some small task, after which it becomes irrelevant. In cases like this, I believe that abbreviated identifiers are acceptable.

Note: Just because the usage of a variable is limited in its scope does not necessarily mean that an meaningless name is okay. If there is a good name that represents what the object does, then it should be used. If you can come up with a variable name that answers 'Why?', then that name is far preferable.

Also, using 'i' and 'j' for for indexes is well understood by developers. By convention, loop counter variables have been named this way since the days of FORTRAN.

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        PerformOperation(i,j);
    }
}
Matt Brunell
great. bc i do this for local variables only (never params or members) and they are always in limited scope! (Just SO MANY of them).
acidzombie24
acidzombie24: don't be so quick to take this as a vote of confidence. Matt says, "I agree with some of the answers here say that variables names should have good names. But I believe that presupposes that an object has *semantic* value. Sometimes, it doesn't." But conversely, **often it does.** Even if the function is less than 20 lines. A 20-line scope does not mean you can call all your integer variables i, j, k, etc. Wait, was `k` the last index checked or the total so far?
itowlson
@itowlson: Yes, I agree with that. I'm adding something to my answer to reflect that.
Matt Brunell
logout
@cudamaru. Loop counter variables are named this way by convention. It's a simple naming pattern with roots in programming history.
Matt Brunell
@Matt. My comment was intended to point out that people may not know why is it the convention and what those roots are. I believe any coding standard worth its salt would say that these are very unhelpful names and people should be discouraged from using them. I apologise in advance for upsetting anyone with this - one of my many personal views on coding styles and standards.
logout
i for index, j and k because they follow i.There's no need to search because single letter variable names should only be used in very small scopes.
David Kanarek
+36  A: 

Write code for humans to read. A good rule of thumb is the bigger the scope in which a variable is used, the more descriptive its name should be. Function parameters especially should have very descriptive names, with the exception of functions where it is obvious what the parameter does, as in
double sqrt(double n)

However, if it's something commonly given a short name and used in a small scope, then use a short name. Examples:

//these are okay
var sb = new StringBuilder();
var sw = new StringWriter();
var cmd = new SQLCommand();
for(var i = 0; i< count; i++) {}
dan
+1 - Bingo. (and more text because this comment was too short...)
Mat Nadrofsky
This is good advice for things whose mere existence defines their job, like StringBuilders or StringWriters where there's usually not much you can say other than "it's building a string, dude." But for things whose purpose could be ambiguous, even in a short scope, a descriptive name is worth while. E.g. `int i` vs. `int index` vs. `int count` vs. `int total`. `int i` doesn't tell us what the int is *for*. The clarity of `int count` pays off even if it's only in scope for three lines.
itowlson
I really disagree on this one. A variable should not be named after the type, but rather after what it contains. Example: If you are using the StringBuilder to build an complex body text for an email then simply name the variable body.
Jan Aagaard
@Jan ok what if you use a StringBuilder to build a query string and later need to convert it to a string and use the string places. Do you expect us to have very short lived variables named `QueryStringBuilder` and `QueryString` ?
Earlz
@Earlz: Well, more or less. I would include the type in the name like you do, I would probably drop 'string' and I would start with a lower cased letter, i.e. `queryBuilder` and `queryString`. But I guess that I might simply have a `StringBuilder query` variable and convert to the string in the return line, like this: `return query.ToString();`.
Jan Aagaard
+7  A: 
def apply_peer_pressure
  while(!code.self_documenting)
    parking_lot.apply_therapy_to(programmer)
  end
end
Wayne Conrad
haha, so i'll be hurt in the parking lot har har.
acidzombie24
Well, only metaphorically. It's the best we can do here.
Wayne Conrad
+2  A: 

It seems like the average length of my variable names increases by one every year I spend writing (and more importantly reading) code.

mattjames
+6  A: 

Some years ago I discovered what happens if I made my functions short:

  • I could understand them. My brain is small, and long functions don't fit.

  • Classes get complicated (lots of functions). But Extract Class produced small, cohesive, single-purpose classes. Again, small brain, so small classes required.

  • The number of variables in a function (or class) is small. Remembering which is which from declaration time to use time is easy, because the distance is short.

  • The number of scopes in my functions is small, so I don't have to figure out which variables go where.

With all of that in place, how I name my variables doesn't matter much. The names don't have to make up for code that is otherwise hard to understand.

Since the number of variables in a scope is small, and the purpose obvious, I rarely need to put any effort in to choosing a descriptive name. Since I don't want to strain my small brain any more than I have to, I never abbreviate. My default name for a variable is the name of the type. E.g. class Foo goes in variable foo. In my code, if it's ever something different, you know something special is happening, and you should pay attention.

In the old days, my no-abbreviation habit would have produce unwieldy code, but since my methods and classes are small, the code doesn't suffer.

Jay Bazuzi
you almost got +1 until I arrived at "I never abbreviate". Now, I have a class called `std::vector< std::pair< std::string, std::map<int, Worker> > >` (that's the short version of the name, BTW). What names should I give its instances?
just somebody
Since my goal is to write code that I can understand, I don't ever write C++. Sorry.
Jay Bazuzi
-1. I don't see how <4 letter variables makes functions shorter. They'll take the same amount of lines. Remembering what the purpose is of each variable instead of having it in the name takes more effort. Even for small functions. I'd really like to see an example of this coding style of yours.
CaptainCasey
@Captain: I don't think that <4 are good idea. I don't abbreviate. I write `StringBuilder stringBuilder = new StringBuilder();` and don't worry whether `sb` means `StringBuilder` or `StreamBuffer`.I do agree that remembering the purpose of a variable takes effort, even for small functions. But when a function is 1-3 lines long the stakes are very low. The number of variables in the function is small. Their purposes are obvious, and mixing them up is hard. Their names are trivial.
Jay Bazuzi
Upvoted for **never abbreviate**.
Jan Aagaard
+2  A: 

It should be immediately clear what any variable is for just by looking at a few lines of code. This can either be due to a nice variable name or the context.

About the only time I use short variable names is either if a short name is entirely descriptive (ie, x & y in a situation dealing with coordinates) or it's a utility function that operates on a data type (ie, capitalize the first letter of this string. It's a string, what else can you say about it? I named it S.)

Loren Pechtel
+2  A: 

Would I consider it a bad coding style? Well, yes.

If you were working with me on same code I'd repeatedly remind you to name your variables better. In short, good code should be readable by other developers without much trouble and good variable names help a lot. Maybe you don't have problems reading your code even after a while, but the question is whether someone who has never worked on that good would be equally fine with it.

There are a few exceptions where I think that short variable names are okay:

Indexes (mostly in for loops) such as:

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

Variables used in a very limited scope, such as Linq queries, lambda expressions or some of the examples already mentioned like Streamwriters and -readers and such are another example where I think that short variable names are fine.

Furthermore it's always a question of how readable your code eventually is. The reason why I would be constantly nagging at people who use short variable names is that for me that it is an indicator that they generally don't care about how readable their code is (especially for others).

Anne Schuessler
+1  A: 
SF.
I dont i didnt explicitly say it in my question (although it isnt hard to tell) but i meant with local variables. I agree with what you said. +1.
acidzombie24
A: 

I don't see any reason to use short variable names that say nothing. We live in 21st century, we've got IDEs with IntelliSense (or other autocompletion)! Just press Ctrl+Space and it will advice you normal name for your variable depending on variable type, e.g.

StringBuilder <Ctrl+Space> stringBuilder;
List<Person> <Ctrl+Space> persons;

It is even easier than to type something like sb or another short name. No reason to use short names anymore.

P.S.: The only exception for me are counters like i, j, k in for loop.

levanovd
Just bc it can generate names it doesnt mean i want to use it. It doesnt seem to work if i use var <Ctrl+Space> and also i can have 2 stringBuilder so it almost be meaningles to have stringBuilder2. Also this doesnt seem to work in 2008 as StringWriter <Ctrl+Space> brings up a list of classes. I still disagree and dont find the names useful.
acidzombie24
If I want to use var, I follow this technique:1. write variable type instead of var 2. generate name3. suggest appropriate constructor (often useful)4. replace type with var (e.g. R# allows to do it with pressing Ctrl-Enter and Enter)So I don't need to type variable name and constructor with only two extra key presses.
levanovd