views:

446

answers:

10

Hi...

I have seen too much C# and C++ code where the variable naming convention seems to ask programmers to write variable names using underscore before the text of the variable. e.gr.

int? _countMoney;

What's the rationale supporting that convention?

+17  A: 

In C# I usually prefix with _ private fields but never local variables. The rationale behind this is that when I need a private variable I type _ and the Intellisense filters the list and it is easier to find. This way I am also able to distinguish between private from local variables and I no longer need to type this.variablename for class fields but simply _variablename.

Darin Dimitrov
+1 for me too, the main idea is filtering of variables.
Lazer
I was doing this long before intellisense in order to distinguish member variables. It was a follow on from C++ days and MS using m_ for member variables
Peter M
If you can't determine whether or not a variable is local or not within a few seconds of looking at a method, could it not be argued that your method might be too complex? As for Intellisense filtering, is writing code tailored to a specific feature of an IDE really a good idea?
Justin Holzer
@Justin: While I agree with your first point, for your second point I have to ask if its really a bad idea? If it doesn't hurt readability, but occasionally helps writability, then why not use it?
Dennis Zickefoose
@Justin re:"is writing code tailored to a specific feature of an IDE really a good idea?" When the IDE in question is the de facto standard IDE for the language I think it is appropriate. It's not much different from using different coding conventions for different languages
Davy8
Although I prefer this.variable ... thanks!
JPCF
@Davy8: In my opinion (which isn't worth much :) ), things like coding standards and naming conventions should be developed irrespective of any tool/framework/IDE. A variable naming convention should make just as much sense to be used in a basic text editor (i.e. Notepad) as it does in a big fancy IDE like Visual Studio or Eclipse. I'm not knocking Darin, or anyone else, for using a technique that helps them write better code. I'm just saying that I don't feel the Intellisense argument is a valid reason for using a particular naming convention.
Justin Holzer
@Justin On matter of principle I agree with you, but in practicality using VS for C# is pretty much an assumption unless stated otherwise. Certain things start making more sense when they become assumable (in a humanistic sense of 90%+ish and not a programming sense of 99.99%), like these days you can ask generally someone "what's your email address" without first asking whether they have one at all. 5-10 years ago you couldn't do that, and similarly for Java you can't assume Eclipse because other IDE's also have a fairly strong foothold. Python you can't assume anything about the editor.
Davy8
Sorry went off on a bit of a tangent there, but was trying to make a (hopefully) cohesive analogy.
Davy8
+3  A: 

It's just an easy way to identify private member variables.

fehays
+4  A: 

Like all other conventions it is about making code easier to understand.

I have seen this as a convention for private fields - in that case, it is very easy to see that a private field is being used.

You can ask the same question about hungarian notation.

Oded
Joel wrote an interesting defense of hungarian notation: http://www.joelonsoftware.com/articles/Wrong.html
Tim Yates
The key is using **Apps Hungarian** notation, not **Systems Hungarian**!
Chad
While I'm not personally a fan of Hungarian notation, if it's being used to describe the value of a variable, I think it is far more acceptable. It's when people use it to denote something like a variable's type that I think it is misused. In Joel's article, he talks about using the "us" prefix to denote "unsafe strings". I would argue that in a modern language, like C#, if you want to use a prefix like that, the code would be more clear if you expanded the prefix "us" to "unsafe".
Justin Holzer
A: 

Sometimes people do that in member variables to help distinguish them from local variables. If you're directly accessing an underscore variable, maybe you should be using a getter/setter for access instead.

Graham Perks
Whats wrong with this answer? I find the point perfectly valid.
Lazer
+1  A: 

Like others have said, that naming convention helps distinguish member variables from locals. This gives two major advantages:

  • Helps pick out places where object state is being modified (important, for example, for thread safety)
  • Prevents naming clashes. I can write a constructor like:

    SomeObject(int foo, int bar)
    {
      _foo = foo;
      _bar = bar;
    }
    

    That way, I don't have to name the arguments new_foo or something like that.

Tim Yates
In C++ at least, you can write a constructor like this: `SomeObject(int foo, int bar) : foo(foo), bar(bar) {}`, and the "correct" thing occurs.
Oli Charlesworth
@Oli: Which doesn't necessarily mean you should actually be doing this...
sbi
True. This is something I learned in my C# days (where member initializer lists aren't allowed, IIRC).
Tim Yates
@sbi: Agreed. I do tend to do exactly this for PODs, though (assuming your definition of "POD" is allowed to encompass a constructor!)
Oli Charlesworth
What would be so bad about dropping the underscore from your member variables and using the "this" keyword?
Justin Holzer
@Justin: To eliminate the possibility of mistakes?
Oli Charlesworth
@Oli: What mistakes? If you're using Visual Studio, or most modern IDEs, the variable name can be automatically completed for you.
Justin Holzer
@Justin: The mistake of not typing `this` before you use the variable.
Dennis Zickefoose
@Dennis: You're still not making a mistake. You can certainly access an instance field without using the "this" keyword
Justin Holzer
@Justin: There are very few circumstances in which `foo = foo;` is not a mistake.
Dennis Zickefoose
@Dennis: There are countless numbers of mistakes that can be made like that, all of which are syntactically valid. Obviously, my opinions aren't shared by others in this thread, and that's fine. My real point is that I feel the most important thing to communicate in a variable name is the intent/purpose of the variable, and adding a prefix like "_" adds no value as far as communicating intent. Regardless of the scope that a variable is defined in, what good is it if you have no idea what it's being used for?
Justin Holzer
In this scenario, I personally would try to better describe "_foo" and "_bar" as something like currentFoo/currentBar or backingFoo/backingBar. In a lot of scenarios, prefixing with "current" describes something shared that is subject to change, and "backing" usually in the case it is something that can be accessed by a property. It really comes down to either company guidelines or personal preference depending on your situation, though.
joseph.ferris
+6  A: 

You should not use _ as a prefix in c++. Names staring with _ are reserved for the compiler.

The most common prefix is c++ is m_ (as in 'member)

For C# its very common to use _.

At my site where we do equal amount of c++ and c# we always use m_ to be consistent

pm100
No, in C++ names starting with _Uppercase are reserved. _lowercase are fine.
Detmar
@Detmar: Actually [it's more complicated than that](http://stackoverflow.com/questions/3650623/trailing-underscores-for-member-variables-in-c/3651336#3651336), but you both still have a point.
sbi
from standard "Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace". In theory you can get away with it, but why skate the edge?
pm100
@pm100: "in the global namespace." Using it to indicate member fields is perfectly safe, not just safe in theory. Using it outside of a class is where where things get iffy, but that's foolish anywhow.
Dennis Zickefoose
The common way for local variables is now suffix with _
Mark
@Dennis: It's perfectly safe as long as oyu don't let that underscore follow by a capital letter. Oh, and then... two consecutive underscores are forbidden, too. If those rules were so easy, people wouldn't mess them up in answers.
sbi
+4  A: 

The Microsoft Guidelines for member naming specifies that you do not use prefixes for fields.

Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields.

You can read Microsoft's guidelines for names here. This just applies to C#, of course.

So Many Goblins
it is still a very common practice that makes loads of sense...
Matt Briggs
I personally dislike the practice of using a prefix. Your IDE should make it clear to you what's a local and what's a member. This is, of course, up to personal taste (or your project coding standards), but this answer gets my +1.
rmeador
This is one of the few guidelines which I happen to disagree with. I use `m_` and `s_` to distinguish between instance and static fields. This is important to me since you should assume that static fields could be accessed by multiple threads and as such you should take care to guard against threading issue. Using the prefixes in this manner makes it easy to see at a glance if there are any problem spots. This convention was proposed by Jeffery Richter who just happened to have a voice in developing this guideline. He must have lost on this particular point :)
Brian Gideon
@rmeador - IDE syntax coloring is not necessarily used in reading, nor does it copy to other environments [e.g., StackOverflow]. The prefix is in your face, and does copy to all environments.
Andy Thomas-Cramer
Indeed, I do try to follow Microsoft guidelines when writing C# code, but my company uses prefixes to denote local variables (l), private member fields (m), static fields (s) and parameters (p). They are, as you say, right up in your face and you cannot not know what an identifier refers to. VS could probably do a better job at helping you distinguish the origin of identifiers, but sadly, it does not unless you do a mouse hover, which is not that helpful in large pieces of code with many identifiers.
So Many Goblins
A: 

Something I noticed by Java devs in Eclipse when I had to do Java work, they wouldn't underscore there vars. Reason being? The members vars were color coded in the IDE...felt no need to do it so to speak. Form habit it came naturally as I found it easy to locate a memebr var in the VS IDE by way of some visual cue...and underscore was it as it it fairly popular. In the rare event you have to look at code in its rawest form...text...those types of things help out tremendously.

Aaron
+1  A: 

I'm not really sure what the rationale is behind this convention. Personally, I do not care for the use of any kind of variable name prefix for denoting the scope of a variable, nor do I particularly care for the use of underscores in naming anything. What's so bad about using the "this" keyword and adopting a convention of lower camel-cased names for private instance/member variables?

public void IncrementFoo()
{
    this.foo += 1;
}

It's only 5 additional characters to type, but it's very explicit. If you've adopted the lower camel-cased convention for your private instance variables, then this tells you right away that you're accessing a private instance/member variable, and you didn't need to use any kind of prefix to denote it.

Justin Holzer
A: 

The _ prefix is pretty essential in VB.NET because it's not case-sensitive. We code in both C# and VB.NET, and for the sake of everyone's sanity it's important to have the same naming conventions in both languages.

Christian Hayter