views:

1636

answers:

24
  • What rules do you use to name your variables?
  • Where are single letter vars allows?
  • How much info do you put in the name?
  • how about for example code?
  • what are your preferred meaningless variable names? (after foo & bar)
  • why are they spelled "foo" and "bar" rather than FUBAR
A: 

I would say try to name them as clearly as possible. Never use single letter variables and only use 'foo' and 'bar' if you're just testing something out (e.g., in interactive mode) and won't use it in production.

Chris Bunch
foo and bar in prod is a fubar :)
BCS
haha, definitely!
Chris Bunch
A: 

locals: fooBar; members/types/functions FooBar interfaces: IFooBar

As for me, single letters are only valid if the name is classic; i/j/k for only for local loop indexes, x,y,z for vector parts.

vars have names that convey meaning but are short enough to not wrap lines

foo,bar,baz. Pickle is also a favorite.

BCS
A: 

I like to prefix my variables with what they're going to be: str = String, int = Integer, bool = Boolean, etc.

Using a single letter is quick and easy in Loops: For i = 0 to 4...Loop

Variables are made to be a short but descriptive substitute for what you're using. If the variable is too short, you might not understand what it's for. If it's too long, you'll be typing forever for a variable that represents 5.

Foo & Bar are used for example code to show how the code works. You can use just about any different nonsensical characters to use instead. I usually just use i, x, & y.

My personal opinion of foo bar vs. fu bar is that it's too obvious and no one likes 2-character variables, 3 is much better!

JFV
Ouch, hungarian notation.
Robert S.
Yeah, nobody likes Hungarian notation any more. But the answer to a subjective question like this isn't "wrong". I don't like to see people penalized for expressing their viewpoints. If everybody agreed, we wouldn't need the question. Let's make room for different points of view.
DOK
For those of you who abhor Hungarian notation, how about putting in an answer recommending against it, and explaining why? Bet you'd get a lot of votes!
DOK
This isn't necessarily Hungarian notation, anyway. Basic type information is "systems" Hungarian, and true Hungarian carries semantic weight beyond the basic type. I.e., sz isn't just a string, it's a zero-terminated string.
erickson
+20  A: 
function startEditing(){
   if (user.canEdit(currentDocument)){
      editorControl.setEditMode(true);
      setButtonDown(btnStartEditing);
   }
 }

Should read like a narrative work.

Tony BenBrahim
+9  A: 

Well it all depends on the language you are developing in. As I am currently using C# I tend you use the following.

camelCase for variables.

camelCase for parameters.

PascalCase for properties.

m_PascalCase for member variables.

Where are single letter vars allows? I tend to do this in for loops but feel a bit guilty whenever I do so. But with foreach and lambda expressions for loops are not really that common now.

How much info do you put in the name? If the code is a bit difficult to understand write a comment. Don't turn a variable name into a comment, ie int theTotalAccountValueIsStoredHere is not required.

what are your preferred meaningless variable names? (after foo & bar) i or x. foo and bar are a bit too university text book example for me.

why are they spelled "foo" and "bar" rather than FUBAR? Tradition

Craig
Also, FUBAR equates to broken. I do hope my example code isn't broken.
Matthew Scharley
+4  A: 
  • I only use single character variables for loop control or very short functions.
for(int i = 0; i< endPoint; i++) {...}

int max( int a, int b) {
    if (a > b)
       return a;
    return b;
}
  • The amount of information depends on the scope of the variable, the more places it could be used, the more information I want to have the name to keep track of its purpose.
  • When I write example code, I try to use variable names as I would in real code (although functions might get useless names like foo or bar).
  • See Etymology of "Foo"
acrosman
A: 

In DSLs and other fluent interfaces often variable- and method-name taken together form a lexical entity. For example, I personally like the (admittedly heretic) naming pattern where the verb is put into the variable name rather than the method name. @see 6th Rule of Variable Naming

Also, I like the spartan use of $ as variable name for the main variable of a piece of code. For example, a class that pretty prints a tree structure can use $ for the StringBuffer inst var. @see This is Verbose!

Otherwise I refer to the Programmer's Phrasebook by Einar Hoest. @see http://www.nr.no/~einarwh/phrasebook/

Adrian
+1  A: 

What rules do you use to name your variables? I've switched between underscore between words (load_vars), camel casing (loadVars) and no spaces (loadvars). Classes are always CamelCase, capitalized.

Where are single letter vars allows? Loops, mostly. Temporary vars in throwaway code.

How much info do you put in the name? Enough to remind me what it is while I'm coding. (Yes this can lead to problems later!)

what are your preferred meaningless variable names? (after foo & bar) temp, res, r. I actually don't use foo and bar a good amount.

Claudiu
A: 

I have always used under_scores for my delimiters between words in a variable name, but have found camelCasing to be a lot faster.

hlfcoding
Ooh, I loathe underscores. But it's good to hear another point of view.
DOK
A: 

I always use single letter variables in for loops, it's just nicer-looking and easier to read.

A lot of it depends on the language you're programming in too, I don't name variables the same in C++ as I do in Java (Java lends itself better to the excessively long variable names imo, but this could just a personal preference. Or it may have something to do with how Java built-ins are named...).

HappyCodeMonkey
+8  A: 

One rule I always follow is this: if a variable encodes a value that is in some particular units, then those units have to be part of the variable name. Example:

int postalCodeDistanceMiles;
decimal reactorCoreTemperatureKelvin;
decimal altitudeMsl;
int userExperienceWongBakerPainScale

I will NOT be responsible for crashing any Mars landers (or the equivalent failure in my boring CRUD business applications).

Jeffrey L Whitledge
Hell YES!!!!! (or you can use a unit caring type. C++ has a lib for that, I have one for D, IIRC a number of other langs have them as well)
BCS
This is a good application of Hungarian notation.
erickson
@erickson: is the original intent of the Hungarian notation: not the type, but rather the intent or use of the variable.
voyager
A: 

I learned not to ever use single-letter variable names back in my VB3 days. The problem is that if you want to search everywhere that a variable is used, it's kinda hard to search on a single letter!

The newer versions of Visual Studio have intelligent variable searching functions that avoid this problem, but old habits and all that. Anyway, I prefer to err on the side of ridiculous.

for (int firstStageRocketEngineIndex = 0; firstStageRocketEngineIndex < firstStageRocketEngines.Length; firstStageRocketEngineIndex++)
{
  firstStageRocketEngines[firstStageRocketEngineIndex].Ignite();
  Thread.Sleep(100);  // Don't start them all at once. That would be bad.
}
Jeffrey L Whitledge
+1  A: 

What rules do you use to name your variables?

  • I need to be able to understand it in a year's time. Should also conform with preexisting style.

Where are single letter vars allows?

  • ultra-obvious things. E.g. char c; c = getc(); Loop indicies(i,j,k).

How much info do you put in the name?

  • Plenty and lots.

how about for example code?

  • Same as above.

what are your preferred meaningless variable names? (after foo & bar)

  • I don't like having meaningless variable names. If a variable doesn't mean anything, why is it in my code?

why are they spelled "foo" and "bar" rather than FUBAR

  • Tradition.
Paul Nathan
4 and 5 are a pair. Example code often has meaningless vars.
BCS
+4  A: 

Pretty much every modern language that had wide use has its own coding standards. These are a great starting point. If all else fails, just use whatever is recommended. There are exceptions of course, but these are general guidelines. If your team prefers certain variations, as long as you agree with them, then that's fine as well.

But at the end of the day it's not necessarily what standards you use, but the fact that you have them in the first place and that they are adhered to.

Charles Graham
+4  A: 

These are all C# conventions.

Variable-name casing

Case indicates scope. Pascal-cased variables are fields of the owning class. Camel-cased variables are local to the current method.

I have only one prefix-character convention. Backing fields for class properties are Pascal-cased and prefixed with an underscore:

private int _Foo;
public int Foo { get { return _Foo; } set { _Foo = value; } }

There's some C# variable-naming convention I've seen out there - I'm pretty sure it was a Microsoft document - that inveighs against using an underscore prefix. That seems crazy to me. If I look in my code and see something like

_Foo = GetResult();

the very first thing that I ask myself is, "Did I have a good reason not to use a property accessor to update that field?" The answer is often "Yes, and you'd better know what that is before you start monkeying around with this code."

Single-letter (and short) variable names

While I tend to agree with the dictum that variable names should be meaningful, in practice there are lots of circumstances under which making their names meaningful adds nothing to the code's readability or maintainability.

Loop iterators and array indices are the obvious places to use short and arbitrary variable names. Less obvious, but no less appropriate in my book, are nonce usages, e.g.:

XmlWriterSettings xws = new XmlWriterSettings();
xws.Indent = true;
XmlWriter xw = XmlWriter.Create(outputStream, xws);

That's from C# 2.0 code; if I wrote it today, of course, I wouldn't need the nonce variable:

XmlWriter xw = XmlWriter.Create(
   outputStream, 
   new XmlWriterSettings() { Indent=true; });

But there are still plenty of places in C# code where I have to create an object that you're just going to pass elsewhere and then throw away.

A lot of developers would use a name like xwsTemp in those circumstances. I find that the Temp suffix is redundant. The fact that I named the variable xws in its declaration (and I'm only using it within visual range of that declaration; that's important) tells me that it's a temporary variable.

Another place I'll use short variable names is in a method that's making heavy use of a single object. Here's a piece of production code:

    internal void WriteXml(XmlWriter xw)
    {
        if (!Active)
        {
            return;
        }
        xw.WriteStartElement(Row.Table.TableName);

        xw.WriteAttributeString("ID", Row["ID"].ToString());
        xw.WriteAttributeString("RowState", Row.RowState.ToString());

        for (int i = 0; i < ColumnManagers.Length; i++)
        {
            ColumnManagers[i].Value = Row.ItemArray[i];
            xw.WriteElementString(ColumnManagers[i].ColumnName, ColumnManagers[i].ToXmlString());
        }
        ...

There's no way in the world that code would be easier to read (or safer to modify) if I gave the XmlWriter a longer name.

Oh, how do I know that xw isn't a temporary variable? Because I can't see its declaration. I only use temporary variables within 4 or 5 lines of their declaration. If I'm going to need one for more code than that, I either give it a meaningful name or refactor the code using it into a method that - hey, what a coincidence - takes the short variable as an argument.

How much info do you put in the name?

Enough.

That turns out to be something of a black art. There's plenty of information I don't have to put into the name. I know when a variable's the backing field of a property accessor, or temporary, or an argument to the current method, because my naming conventions tell me that. So my names don't.

Here's why it's not that important.

In practice, I don't need to spend much energy figuring out variable names. I put all of that cognitive effort into naming types, properties and methods. This is a much bigger deal than naming variables, because these names are very often public in scope (or at least visible throughout the namespace). Names within a namespace need to convey meaning the same way.

There's only one variable in this block of code:

        RowManager r = (RowManager)sender;

        // if the settings allow adding a new row, add one if the context row
        // is the last sibling, and it is now active.
        if (Settings.AllowAdds && r.IsLastSibling && r.Active)
        {
            r.ParentRowManager.AddNewChildRow(r.RecordTypeRow, false);
        }

The property names almost make the comment redundant. (Almost. There's actually a reason why the property is called AllowAdds and not AllowAddingNewRows that a lot of thought went into, but it doesn't apply to this particular piece of code, which is why there's a comment.) The variable name? Who cares?

Robert Rossney
A: 

It's pretty much unimportant how you name variables. You really don't need any rules, other than those specified by the language, or at minimum, those enforced by your compiler.

It's considered polite to pick names you think your teammates can figure out, but style rules don't really help with that as much as people think.

Mnebuerquo
+3  A: 

What rules do you use to name your variables?

Typically, as I am a C# developer, I follow the variable naming conventions as specified by the IDesign C# Coding Standard for two reasons

1) I like it, and find it easy to read. 2) It is the default that comes with the Code Style Enforcer AddIn for Visual Studio 2005 / 2008 which I use extensively these days.

Where are single letter vars allows?

There are a few places where I will allow single letter variables. Usually these are simple loop indexers, OR mathematical concepts like X,Y,Z coordinates. Other than that, never! (Everywhere else I have used them, I have typically been bitten by them when rereading the code).

How much info do you put in the name?

Enough to know PRECISELY what the variable is being used for. As Robert Martin says:

The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent. From Clean Code - A Handbook of Agile Software Craftsmanship

Furis
+1  A: 

The rules I adhere to are;

Does the name fully and accurately describe what the variable represents?

Does the name refer to the real-world problem rather than the programming language solution?

Is the name long enough that you don't have to puzzle it out?

Are computed value qualifiers, if any, at the end of the name?

Are they specifically instantiated only at the point once required?

Pace
A: 

I do a lot of php in nowadays, It was not always like that though and I have learned a couple of tricks when it comes to variable naming.

//this is my string variable $strVar = "";

//this would represent an array $arrCards = array();

//this is for an integer $intTotal = NULL:

//object $objDB = new database_class();

//boolean $blValid = true;

Ronald Conco
+4  A: 

Read Code Complete, it deals with issues like this, and has statistics about how it influences the quality of the code.

GvS
A: 

Kent Beck's book "Implementation Patterns" has a chapter about naming conventions.

dhiller
A: 

Since I work as a contractor, moving among different companies and projects, I prefer to avoid custom naming conventions. They make it more difficult for a new developer, or a maintenance developer, to become acquainted with (and follow) the standard being used.

So, while one can find points in them to disagree with, I look to the official Microsoft Net guidelines for a consistent set of naming conventions.

With some exceptions (Hungarian notation), I think consistent usage may be more useful than any arbitrary set of rules. That is, do it the same way every time.

.

DOK
+1  A: 

What rules do you use to name your variables? camelCase for all important variables, CamelCase for all classes

Where are single letter vars allows? In loop constructs and in mathematical funktions where the single letter var name is consistent with the mathematical definition.

How much info do you put in the name? You should be able to read the code like a book. Function names should tell you what the function does (scalarProd(), addCustomer(), etc)

How about for example code?

what are your preferred meaningless variable names? (after foo & bar) temp, tmp, input, I never really use foo and bar.

Alexander K
+1  A: 

I never use meaningless variable names like foo or bar, unless, of course, the code is truly throw-away.

For loop variables, I double up the letter so that it's easier to search for the variable within the file. For example,

for (int ii=0; ii < array.length; ii++)
{
    int element = array[ii];
    printf("%d", element);
}
Randy Stegbauer
an interesting approach, It would be fun to get a table of uncommon letter pairs and use them.
BCS