views:

2201

answers:

24

What do you use to denote a member variable in a class?

The most common time this is a problem is when you have a parameter passed into a constructor to set a member variable. Here is an example:

public MyClass(string name)
{
    name = name;  // arghh!!
}

I've used m_name before, but that stinks of Hungarian. I've used _name before, (I think I like that one best right now.) I've done the whole public MyClass(string n), to make the variable different, but that really stinks IMO. I've done the this.name before, but that seems burdensome to put everywhere you mention a member variable, and its hard to enforce.

Anyone have a good reason why one is better than another? Or what do you use?

This can be language agnostic.

Related:
http://stackoverflow.com/questions/151594/whats-a-good-naming-convention-for-large-scope-function-variables

+4  A: 

name_ seems to be another common "standard".

Ferruccio
And a pretty terrible one, in my opinion. What does the "_" mean?
Joachim Sauer
I just threw up a little
Greg Dean
It's a C++ standard, and the reason it's a trailing underscore is because anything with a leading underscore is reserved and should not be used. I'm also the only person at my company that doesn't think this is really ugly ;)
MadKeithV
It is ugly. It still is (reputed to be) a standard. It is better than the leading underscore version - but it is still ugly.
Jonathan Leffler
This is how I name member variables in C++. I find it quite logical and not unattractive. @MadKeithV correctly points out the reason to shy away from leading underscores, and 'm_' always seemed uglier to me. Same names make initializer lists look funky to me (see @Danko's answer), while WhatevClass(int foo, int baz) : foo_(foo), baz_(baz) {} is readable and obvious. IMHO, of course.
Derrick Turk
+63  A: 

Why change a perfectly fine naming scheme, just because of one little bump in the road?

public MyClass(string name)
{
    this.name = name;
}
Joachim Sauer
this is where this shines :)
annakata
Exactly. Don't waste time thinking of a new variable name, when you've already got a perfectly descriptive one.
Bill the Lizard
Wow that's good.. :)
krebstar
And this way is approved by MS StyleCop :)
PiRX
When using R#, it grays out unused variables, so you can identify quickly when this. is missing. I always use this naming scheme.
Think Before Coding
@Think: most good compilers/IDEs will warn you about common errors with these constructs "name = name;" will usually be marked as an assignment with no effect.
Joachim Sauer
A great potential... for mistakes! Forget to put "this" and you're in trouble.
Rui Curado
@Rui: that why you should be using capable tools that tell you about those mistakes.
Joachim Sauer
@Rui: Just use THIS all the time for global and you won't have any error...
Daok
+13  A: 

"m_" hardly stinks of Hungarian, it has no type information in it at all. It does provide a handy means of reminding you that it is a member variable though, which can mean the difference between your code working and a few days of debugging.

So, I use m_ and don't worry myself about whether it 'stinks' or not, it works well and isn't intrusive.

gbjbaanb
the 'this' operator does the exact same thing, arguably better.
Greg Dean
m_ takes less time to write... and uses less space.
Tim
I would argue agains that, Greg. m_, p_, g_ and s_ are great little tells and m_ tends to be the MFC standard. Oh member, parameter, global, static. It's easier to have one convention for them all, then to switch it up for member and globals and such.
baash05
I have seen l_ for local variables, but that seemed too OTT for me. I just use m_ and g_, simple and easy.
gbjbaanb
OH.. strickly speaking m_ is hungarian notation. There are two types of hungarian and it falls under one of them.. Not all hungarian is bad. This is a case on point.
baash05
m_ etc might seem handy, but we have tools that can tells us what type of variable a variable is. Make the code look nicer and be easier to read, m_ is just ugly and the human eye isn't trained to read it.
Neil Barnwell
m_ doesn't tell you anything about the variable type...
gbjbaanb
+9  A: 

In a language like Java, I'd just do:

public MyClass(String name)
{
    this.name = name;
}

In cases in which the member variable is not shadowed, I'd just do name.

I never prefix with m or m_. It always seemed kind of nonsensical to me.

mipadi
+3  A: 

In C# I use properties starting with uppercase characters. If these are backed by fields with lowercase names (i.e., not automatic properties), and I need to use the backing field for some reason I always precede with this. Usually I precede my properties with this as well.

public string Property { get; private set; }

public MyClass( string property )
{
    this.Property = property;
}
tvanfosson
I don't think having two things that differ solely by case is a good idea. Adding the "this." helps...but not enough.
Michael Haren
I try to avoid this, as well. FxCop, and Code Analysis in VS 2008, have a rule about this. CA1708 - IdentifiersShouldDifferByMoreThanCase. (http://msdn.microsoft.com/en-us/library/ms182242.aspx).
joseph.ferris
I would agree in the cases where the variable has the same scope, but I think it's perfectly ok when the lowercase version is the backing field for a property or one is a parameter to a function. Avoiding the right name for a variable or resorting to prepending various prefixes is, IMO, worse than using the right name even with it is the lowercase version of an existing property. I wouldn't, for example, have two properties that differ only in case, but I think the example I gave is perfectly acceptable and not ambiguous (obviously).
tvanfosson
+12  A: 

When doing .NET projects have used the _ prefix. So the code looked something like:

public MyClass(String name)
{
    this._name = name;
}

alt. code would be:

public MyClass(String name)
{
    _name = name;
}

and finally some of my code looks like:

public MyClass(String psName)
{
    this._name = psName;
}

I know that "_" could have questionable meaning but with repeat usage it is actually quite obvious...

Frank V
This prefix is not needed in C# because of the this keyword.
Daok
right, it isn't but I still use it to distinguish member fields for when I don't use the this keyword.
Frank V
the _ has questionable meaning in that its traditionally used to denote a 'hidden' variable: don't go against convention as you just confused everyone. In C/C++ it denotes a reserved word often used in a library implementation.
gbjbaanb
I've never actually heard about this... I guess it depends on the team you are working with. Every team I've worked with doesn't mind this notation. I mostly use C#, so in general this might not be a good practice...
Frank V
@gbjbaanb that's exactly right, the intention of starting a variable name with _ is to denote that it is hidden. That is why the private instance fields should be named using that convention. They are internal to the implementation of the class and should not be accessed by other types. With proper OO design, these private instance fields must be encapsulated by a property or getter and setter or other accessor methods.
Tion
A: 

If it's an instance variable i prefix with "m_". If it's a static variable I prefix with "_".

Micah
A: 

m_ hardly "stinks of hungarian". It works, it's widely used and I see no real good arguments against it.

EDIT

This has possibility of turning into an (ugly) religious war.

Just pick a convention and stick with it.

Tim
A: 

I'm the opposite of @Micah, I use the prefixes "_" for member, "g_" for global and "s_" for static. To each his own, just follow a standard.

kenny
global? Where do you have globals? Are globals = to member variables?
Frank V
A: 

I tend to go with m_ mostly because it's the windows standard, and reading windows code becomes easier if you have the same style. I've seen the _ for members in older c++ but I kinda like the flexiblity of the m. I put:

m_ in front of members (instance) variables.
s_ in front of statics
g_ in front of globals (that arn't constants)
p_ in front of parameter variables (aka arguments).

I've seen others use a_ instead of p_

public MyClass(string p_name)
{
    m_name = p_name;
}

I don't like the "this." partially because it's not as language agnostic as the m_ and partly because I use the prefix for globals, parameters and statics.
Also the "this" would make your code harder to read.. "this" in my IDE shows up as blue while the text around it is black. That makes it stand out, when I'd rather have the variables more homogenious and only have controle statments different.

baash05
Change your IDE's color settings.
jmucchiello
+3  A: 

Personally, I find using m_ for instance variables clutters the code a bit.

I'd go with tvanfosson's approach, using .NET 3.5's automatic properties. There's less code to write, and there should be no confusion between constructor arguments and instance variables (unless you decide to capitalize your arguments too...)

Pwninstein
+1  A: 

I use:

  • m_name for member variables
  • s_name for static member variables
  • NAME for constants.

Clean Code, which by the way is an excellent book, doesn't recommend using m_ but I think this is one of the few places where Uncle Bob is wrong. Even though syntax highlighting can help you distinguish between member and local variables I have seen at least three bugs this year because of mix ups, all by different people using Eclipse.

Also, m_ looks a bit ugly and I believe this is good. This can prevent developers from accessing the member variable directly without using a getter/setter, e.g. myObject.m_name, and if it looks ugly people hesitate before creating one more member variable when a local one would just do fine.

I would be okay with this.name if you could force the compiler/IDE to only accept that notation when you refer to member variables.

Kire Haglin
+1  A: 

public MyClass(String name) { this.name = name; }

A: 

I use quite a long winded convention. I always prefix member variables with "this" and they are also always prefixed with "m_". Then I use Hungarian Notation to type hint.

this.m_sValue

Similarly, arguments passed into a function are always prefixed with "a_", eg.

a_sArgumentOne, a_iArgumentTwo

michael
whoever marked me down could at least have left a comment?!
michael
A: 

I always do (in Java):

public class Foo{
  int _foo;

  public void bar( int foo_ ){
    _foo = foo_;
  }
}

So _ before member variables and _ after arguments. Pretty common, I believe.

Cambium
+1  A: 

I prefer the _name notation for private instance fields. I've found that hitting _ followed by Ctrl+Enter to get IntelliSense to list my privates is extremely handy!

Another thing I like to do is name by private methods as camelCased. This provides a very easy and very quick way to distinguish between private and public/protected methods, not just when looking through the code-file itself, but also looking through call-stacks. Of course, I don't use this for private properties, as, IMO, they should not exist!

Steve Dunn
A: 

I chose the simplest and easiest solution:

String _name;

public Test(String name)
{
    _name = name;
}

Using this.name, or m_name all work fine, but why overcomplicate your code, even by a little bit?

The only exception is when I'm using automatic properties:

public String Name { get; set; }

public Test(String name)
{
    Name = name
}
weiran
A: 

In C# I've grown fond of:

_variable = private/protected class member

Variable = public accessor

variable = function parameter

toast
A: 

I prefer iName - a Symbian C++ naming convention (more here). Symbian has a set of conventions designed to help developers communicate ownership and cleanup intent (to avoid potential memory leaks) and although it's a bit clunky to start with, it makes a lot of sense. Though maybe it's just habitual now...

+2  A: 

Although apparently Microsoft recommend against m_ and _, I was under the belief that, as .NET is an open standard that can be implemented by any language, those languages could include languages that are not case sensitive, so in order to allow local variables and attributes to have the same name without declaring the name twice, we should include underscores to differentiate member variables and Properties.

for example:

private int number

public int Number { get; set; }

would not be applicable in, say, Delphi.Net. That being said, if the above code was referenced by a Delphi.NET project by assembly, the private variable name should not be an issue. Nonetheless, I would definitely use

private int _number

public int Number { get; set; }
johnc
exactly, this is optimal in all ways and conveys the right information with the fewest number of keystrokes.
Tion
A: 

In C++, I don't prefix/suffix member variables if I'm exposing them as public. Also, if you're using member initialization lists, you can actually use the same name for a constructor parameter, so this code works:

struct FooBar
{
    int foo;
    int bar;

    FooBar( int foo, int bar ) : 
     foo( foo ), 
     bar( bar )
    {
    }
};

There is a good article about class instance initialization which describes this "trick". See also 12.6.2.7 in the C++ standard.

Danko Durbić
A: 

the gcc flag -Wshadow gives me a warning when i use the following

class a
{
int x ;

public:

void fun(int x) { this->x = x } ;
} ;
awhan
A: 

Well if the code is actually that simple, I do this:

public MyClass(string newName)
{
    this.name = newName; //You can omit "this.", but having it there makes the code more clear.
}

But really, it doesn't matter how you do it, so long as it's consistent.

Wallacoloo
+2  A: 

Well, name conventions were more significant in days when IDEs were not as powerful as today. Infact, it was plain notepad which we worked on. I would have completely agreed with people to follow conventions like m_ , s_, etc prefixes for different types of variables.

But, Nowadays, we work on much improved IDEs where it is much easier to traverse across the files and see the scope of variables and methods. Features like autocomplete, refactor, generate codes and zillions of those are at our disposal these days.

It makes little sense to follow such prefixes, especially when it interferes with the readability of the code.

Thoughts!!!

Mohd Farid