Member Variables Naming Convention

C

Cor Ligthert [MVP]

Hans,

At a certain moment you will see that you are using it by accident in normal
letters. Sometimes it is even then very handy to use.

:)

Cor
 
M

Michael Nemtsev

Hello Dave,

DS> Hi Michael,
DS>DS> Well, "_" doesn't seem to provide any value that doesn't exist using
DS> the standard notation. If I see something like, "firstNumber" in a
DS> method body it's usually obvious to me whether its a field or a
DS> parameter just by quickly scanning the method, considering that the
DS> method was properly designed to be succinct, or even just by context
DS> and its chosen name.

Right

DS> In larger methods a simple mouse-over does the
DS> trick. Intellisense tells us when a variable is a "local variable"
DS> (although I rarely even need that information from intellisense, if
DS> ever). Otherwise, when "(local variable)" isn't displayed, it's a
DS> field.

Ok, now u was asked to review the code. You got 2 version of source files
from CVS, open them in diff editor and starting review changes. There is
no intellisence. An catch that difference u described above is really hard

DS> And, if an object is confusing to the point where something
DS> such as "firstNumber" isn't obviously a field or a local variable,
DS> then the chosen name might not be descriptive enough.

What do u suggest for naming convention to distinguish locals/fields?
We are not in the perfect world where is the each method is on the screen's
lenght.

it's a little bit simple if we use encapsulation, where no direct access
to fieds, only properties - camel case for private and pascal for public
fields. but we are again stumble over ambiguity between the local variable
and the private property


DS> So the best argument for "_" so far is that it alleviates parameter
DS> ambiguity without requiring "this.", which I actually prefer over
DS> "_" anyway. Furthermore, "this." has been standardized while "_" is
DS> not recommended by Microsoft.

I don't like "_" too, but it seems to be the simplest and neat solution




DS>
DS> DS>
Hello Dave,
DS> DS> public ClassConstructor(int firstNumber, int secondNumber)
DS> {
DS> _FirstNumber = firstNumber;
DS> this.secondNumber = secondNumber;
DS> }
DS> What does "_" provide over the standard, excluding the above?
that means that "_FirstNumber" is the private/protected property.
It doesn't matter what do u use to differentiate between
private/protected and public, I just take
the position that we really need the way to show the difference.
Either _ or m_ or whatever
possible.
MS codingstyle suggests nothing for this
DS> But other than the example above, does an "_" prefix provide any
DS> value?

Maybe not quite undestand u - it provides anything, just mark that we
deal with private/property item.

Any other ideas how to underpin this?

---
WBR,
Michael Nemtsev [C# MVP] :: blog: http://spaces.live.com/laflour
"At times one remains faithful to a cause only because its opponents
do not cease to be insipid." (c) Friedrich Nietzsche
---
WBR,
Michael Nemtsev [C# MVP] :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsch
 
B

Bruce Wood

Dave said:
But other than the example above, does an "_" prefix provide any value?

I hated the idea when a coworker introduced it, but now I'm all for it.
We're gradually converting our code over to using the "_" prefix for
member variables. Here's why.

Keep in mind that most of us are no longer writing code in text editors
and peering at printouts. Most of us are using Visual Studio and
Intellisense. I think that Hungarian Notation was a good idea for
assembly language, but it should have a stake driven through its heart
these days because if I want to know what type something is, I mouse
over it and VS tells me. So, there are now TWO considerations: the
written code itself, and the code within the Visual Studio environment.

With this in mind, we had an annoying problem when we followed what
appear to be MS's official guildelines. Given code like this:

public class Blah
{
private int foo;

public int Foo { get { return this.foo; } set { this.foo = value; }
}
}

and remembering that Intellisense is case-INsensitive, one can
immediately see why Intellisense has the annoying habit of choosing one
of this.foo or this.Foo "at random" when I type "this.f" from inside
the Blah class scope. This led to not a few bugs in our code, as touch
typists like me who often type without watching the screen would end up
with references to the property instead of to the member variable. I
lost count of how many infinite loops I introduced that way.

The "_" introduced two improvements. First, it's unambiguous when typed
in VS: "this._f" always means you want a member variable starting with
f, whereas "this.f" or "this.F" always indicates something public,
probably a property or method.

Second, all member variables appear at the top of the list in the
debugger, so you don't have to go hunting for them.

Does it make the code or less readable on printout? Doesn't much matter
to me. It does, however, make VS easier to use, and since that's where
I spend most of my coding and debugging time, that matters a lot.
 
M

Michael C

Dave Sexton said:
Personally, I think "m_" and "_" are legacy notations and I find them to
be annoying, without any value. I just use lower camel case everywhere.

I can't argue with you on _ being annoying, that is a matter of taste but I
think the statement that it is without any value isn't true. The value is of
course that it shows what is a member variable and it allows properties to
have the same name as the variable. It also avoids the problem of using only
case to distinguish 2 different items, something which I prefer to avoid. It
also makes it easy to find all member vars in intellisense (something that
prefixing with m never did). I can understand disputing the usefulness of
this "value" but I don't think you can argue that no value exists.

Michael
 
R

Registered User

I think consistency is important.

You're dead on target. Regardless of the naming convention used in a
project, consistency is the crux of the biscuit. If the convention
isn't followed it is of no value.

The OP wrote of programmers being confused by different naming
conventions. The responses indicate a great deal of personal
preference but no tales of confusion have been told.

regards
A.G.
 
R

Registered User

You're dead on target. Regardless of the naming convention used in a
project, consistency is the crux of the biscuit. If the convention
isn't followed it is of no value.
I got this wrong. It wasn't the OP but a followup that mentioned
confusion.
 
M

Mattias Sjögren

Dave,

These guidelines are primarily for publicly accessible members.

"The goal of the .NET Framework design guidelines is to encourage
consistency and predictability in *public APIs* while enabling Web and
cross-language integration." (Emphasis added)

http://msdn.microsoft.com/library/d...ef/html/cpconnetframeworkdesignguidelines.asp

And more clearly

"Casing and naming guidelines apply only to public and protected
identifiers, and privately implemented interface members. Teams are
free to choose their own guidelines for internal and private
identifiers."

http://blogs.msdn.com/kcwalina/archive/2004/09/28/235232.aspx


Mattias
 
D

Dave Sexton

Hi Michael,
I can't argue with you on _ being annoying, that is a matter of taste but I think the statement
that it is without any value isn't true. The value is of course that it shows what is a member
variable and it allows properties to have the same name as the variable. It also avoids the
problem of using only case to distinguish 2 different items, something which I prefer to avoid. It
also makes it easy to find all member vars in intellisense (something that prefixing with m never
did). I can understand disputing the usefulness of this "value" but I don't think you can argue
that no value exists.

I wasn't questioning its use, I was questioning its value.

And I can argue that no value exists - I did in another post :)
 
D

Dave Sexton

Hi Michael,

DS> In larger methods a simple mouse-over does the
DS> trick. Intellisense tells us when a variable is a "local variable"
DS> (although I rarely even need that information from intellisense, if
DS> ever). Otherwise, when "(local variable)" isn't displayed, it's a
DS> field.
Ok, now u was asked to review the code. You got 2 version of source files from CVS, open them in
diff editor and starting review changes. There is no intellisence. An catch that difference u
described above is really hard


Ok, you're definitely correct that intellisense and tooltips aren't always available :)

But if the method's purpose is known and variable names are meaningful, I don't see how that could
be a problem. It's never been a real problem for me, at least not enough to warrant the use of an
"_" before all fields in my entire system and to go against a standard.
DS> And, if an object is confusing to the point where something
DS> such as "firstNumber" isn't obviously a field or a local variable,
DS> then the chosen name might not be descriptive enough.

What do u suggest for naming convention to distinguish locals/fields?
We are not in the perfect world where is the each method is on the screen's lenght.

In VS, context should be enough, or use descriptive names, or it shouldn't matter:

class Color
{
byte r, g, b;

public void ConvolutedRandomization(int factor)
{
// It doesn't matter whether "rnd" is a field or local variable, later in code.
// The instance will be used regardless of its origin.
Random rnd = new Random();

// It doesn't matter, later in code, whether randomR is a field or a local.
// The only thing we'll care about when its required is its value.
byte randomR = (byte) rnd.Next(0, Math.Min(256, factor))
byte randomG = (byte) rnd.Next(0, Math.Min(256, factor))
byte randomB = (byte) rnd.Next(0, Math.Min(256, factor))

// we know we're assigning to fields because that's the purpose
// of this method.
r = Math.Min(256, r * randomR);
g = Math.Min(256, g * randomG);
b = Math.Min(256, b * randomB);
}
}


class Color
{
byte _r, _g, _b;

public void ConvolutedRandomization(int factor)
{
Random rnd = new Random();

byte randomR = (byte) rnd.Next(0, Math.Min(256, factor))
byte randomG = (byte) rnd.Next(0, Math.Min(256, factor))
byte randomB = (byte) rnd.Next(0, Math.Min(256, factor))

_r = Math.Min(256, _r * randomR);
_g = Math.Min(256, _g * randomG);
_b = Math.Min(256, _b * randomB);
}
}

You might feel that it's much clearer in the latter version whether "_r" is a local or a field, but
does that provide any value? After all, if you understand the method then it should be obvious, and
anyway there really is no ambiguity here. Why even assume that "r", in the first example, is a
local variable?
it's a little bit simple if we use encapsulation, where no direct access to fieds, only
properties - camel case for private and pascal for public fields. but we are again stumble over
ambiguity between the local variable and the private property

Outside of VS, as you pointed out, it may be a problem. Definitely not inside, however.

<snip>
 
D

Dave Sexton

Hi Bruce,
I hated the idea when a coworker introduced it, but now I'm all for it.
We're gradually converting our code over to using the "_" prefix for
member variables. Here's why.

Keep in mind that most of us are no longer writing code in text editors
and peering at printouts. Most of us are using Visual Studio and
Intellisense. I think that Hungarian Notation was a good idea for
assembly language, but it should have a stake driven through its heart
these days because if I want to know what type something is, I mouse
over it and VS tells me. So, there are now TWO considerations: the
written code itself, and the code within the Visual Studio environment.

With this in mind, we had an annoying problem when we followed what
appear to be MS's official guildelines. Given code like this:

public class Blah
{
private int foo;

public int Foo { get { return this.foo; } set { this.foo = value; }
}
}

and remembering that Intellisense is case-INsensitive, one can
immediately see why Intellisense has the annoying habit of choosing one
of this.foo or this.Foo "at random" when I type "this.f" from inside
the Blah class scope. This led to not a few bugs in our code, as touch
typists like me who often type without watching the screen would end up
with references to the property instead of to the member variable. I
lost count of how many infinite loops I introduced that way.

But I've already stated that I never use "this." unless I must resolve an ambiguity issue for the
compiler. It's pointless there, and you've also proven that it may be dangerous as well.
The "_" introduced two improvements. First, it's unambiguous when typed
in VS: "this._f" always means you want a member variable starting with
f, whereas "this.f" or "this.F" always indicates something public,
probably a property or method.

That's a good point if you're using "this." everywhere, which I know a lot of programmers do. I
don't because it's more typing and provides no real value, IMO.
Second, all member variables appear at the top of the list in the
debugger, so you don't have to go hunting for them.

Good, descriptive names and code layout alleviate the need to search for members based on their
member type in a large intellisense list.

Normally, just typing "f Ctrl+Space" is enough to find "foo", otherwise it probably shouldn't be
named "foo" in the first place. And even if it's unavoidable that "foo" will be difficult to find
using intellisense due to an overwhelming number of fields in a class, or other complexities, you
could also code like I do and group all private fields together. I've posted my layout snippets
after my sig.
Does it make the code or less readable on printout? Doesn't much matter
to me. It does, however, make VS easier to use, and since that's where
I spend most of my coding and debugging time, that matters a lot.

I agree that VS is more important than outside of VS since that's where the large majority of my
time is spent as well.

--
Dave Sexton


All of my structs and classes (components and non-components) use the following layout, so it's very
easy to locate the names of fields. As a matter of fact, I often have the Private / Protected
region expanded when I'm coding methods so I don't have to browse through a long list of fields in a
complex object. I'm sure that helps me locate unknown field names much faster than browsing a list
of members that all begin with "_".

(Watch for tabbing issues if anyone tries to use the snippets since I pasted them here and the
formatting was probably lost)

{ layout.snippet }

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>layout</Title>
<Shortcut>layout</Shortcut>
<Description>Code snippet for region layout of code files</Description>
<Author>Dave Sexton</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal Editable="false">
<ID>class</ID>
<Function>ClassName()</Function>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[#region Public Properties
#endregion

#region Private / Protected
#endregion

#region Constructors
/// <summary>
/// Constructs a new instance of the <see cref="$class$" /> class.
/// </summary>
public $class$($end$)
{
}
#endregion

#region Methods
#endregion

#region Events
#endregion

#region Event Handlers
#endregion

#region Nested
#endregion]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

{ layoutc.snippet }

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>layoutc</Title>
<Shortcut>layoutc</Shortcut>
<Description>Code snippet for region layout of code files that contain a class that can be edited
in a designer (derived from Component)</Description>
<Author>Dave Sexton</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal Editable="false">
<ID>class</ID>
<Function>ClassName()</Function>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[#region Public Properties
#endregion

#region Private / Protected
$end$
#endregion

#region Constructors
/// <summary>
/// Constructs a new instance of the <see cref="$class$" /> class.
/// </summary>
public $class$()
{
InitializeComponent();
}
#endregion

#region Methods
#endregion

#region Events
#endregion

#region Event Handlers
#endregion

#region Nested
#endregion]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
 
D

Dave Sexton

Hi Mattias,

In a different post than the one to which you replied I added a different link that is contrary to
your statement. Here it is again:

"Field Usage Guidelines [.NET Framework]"
http://msdn.microsoft.com/library/d...html/cpconfieldusageguidelines.asp?frame=true

It's quite clear that they are referring to private fields. Scroll to the example at the bottom and
read the nearby bullets.

--
Dave Sexton

Mattias Sjögren said:
Dave,

These guidelines are primarily for publicly accessible members.

"The goal of the .NET Framework design guidelines is to encourage
consistency and predictability in *public APIs* while enabling Web and
cross-language integration." (Emphasis added)

http://msdn.microsoft.com/library/d...ef/html/cpconnetframeworkdesignguidelines.asp

And more clearly

"Casing and naming guidelines apply only to public and protected
identifiers, and privately implemented interface members. Teams are
free to choose their own guidelines for internal and private
identifiers."

http://blogs.msdn.com/kcwalina/archive/2004/09/28/235232.aspx


Mattias
 
D

Dave Sexton

Hi,

Isn't there value in constancy across an entire community as well?

Have you not had to work with code where someone else took their own liberties in choosing what was
appropriate as standards (even if consistent with their organization's standards when the code was
written), leaving you weeping, pulling out hair and going for coffee every 20 minutes?

;)
 
M

Michael Nemtsev

Hello Dave,

DS> Ok, you're definitely correct that intellisense and tooltips aren't
DS> always available :)
DS> But if the method's purpose is known and variable names are
DS> meaningful, I don't see how that could be a problem. It's never
DS> been a real problem for me, at least not enough to warrant the use
DS> of an "_" before all fields in my entire system and to go against a
DS> standard.

Completly agree, but....

DS> Outside of VS, as you pointed out, it may be a problem. Definitely
DS> not inside, however.

.... but we returned to my OP :)
What's the most interesting that the widely-accepted standardization is
tuned a little bit to suite company best practice.

So, if someone practice is the intensive codereview (for example PSP metholody
in team) thus this evil "_" only helps u.
In my practice, for some workplaces where I worked, we had spent at least
2-3 hours/per day for code-reviewing, and we found out that "_" really helps
us

Dave, we've got to the same conclusion with good understanding each other.
Suggest to close this discussion :)

---
WBR,
Michael Nemtsev [C# MVP] :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
D

Dave Sexton

Hi Michael,
DS> Ok, you're definitely correct that intellisense and tooltips aren't
DS> always available :)
DS> But if the method's purpose is known and variable names are
DS> meaningful, I don't see how that could be a problem. It's never
DS> been a real problem for me, at least not enough to warrant the use
DS> of an "_" before all fields in my entire system and to go against a
DS> standard.

Completly agree, but....

DS> Outside of VS, as you pointed out, it may be a problem. Definitely
DS> not inside, however.

... but we returned to my OP :)

I spend most of my time in VS. The cons outweigh the pros, IMO.

--
Dave Sexton

Michael Nemtsev said:
Hello Dave,
What's the most interesting that the widely-accepted standardization is
tuned a little bit to suite company best practice.

So, if someone practice is the intensive codereview (for example PSP metholody in team) thus this
evil "_" only helps u.
In my practice, for some workplaces where I worked, we had spent at least 2-3 hours/per day for
code-reviewing, and we found out that "_" really helps us

Dave, we've got to the same conclusion with good understanding each other. Suggest to close this
discussion :)

---
WBR,
Michael Nemtsev [C# MVP] :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not cease to be insipid."
(c) Friedrich Nietzsche
 
D

Dave Sexton

D

Dave Sexton

Hi Michael,

I'm sorry, but I didn't see the end of your post (I'm switching back and forth from newsgroups to
work right now when I build :)

That's fine with me. Our experiences obviously differ :)

Thanks for the discussion.

--
Dave Sexton

Michael Nemtsev said:
Hello Dave,

DS> Ok, you're definitely correct that intellisense and tooltips aren't
DS> always available :)
DS> But if the method's purpose is known and variable names are
DS> meaningful, I don't see how that could be a problem. It's never
DS> been a real problem for me, at least not enough to warrant the use
DS> of an "_" before all fields in my entire system and to go against a
DS> standard.

Completly agree, but....

DS> Outside of VS, as you pointed out, it may be a problem. Definitely
DS> not inside, however.

... but we returned to my OP :)
What's the most interesting that the widely-accepted standardization is
tuned a little bit to suite company best practice.

So, if someone practice is the intensive codereview (for example PSP metholody in team) thus this
evil "_" only helps u.
In my practice, for some workplaces where I worked, we had spent at least 2-3 hours/per day for
code-reviewing, and we found out that "_" really helps us

Dave, we've got to the same conclusion with good understanding each other. Suggest to close this
discussion :)

---
WBR,
Michael Nemtsev [C# MVP] :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not cease to be insipid."
(c) Friedrich Nietzsche
 
J

Jon Skeet [C# MVP]

Dave Sexton said:
Following standards provides real value through consistency.
Not following any standards makes
development harder by creating friction when moving amongst
different notations and conventions. Making up your own standards makes
interoperability harder, inevitably making development harder as
well - even if its not harder for you it will be for someone else one
day that has to work with your atypical code.

Those are all good reasons for sticking to the standard conventions for
*public* members, but it's worth noting that as far as I'm aware MS
doesn't have any conventions for *private* members. I've seen some
Rotor code which has three different private naming conventions within
the same class - now *that's* something to avoid.

I'd say that so long as your convention for private members is sensible
in itself and consistently applied, it doesn't matter too much what it
is. I use m_ at work and plain camel case for personal development - no
problems.
 
J

Jon Skeet [C# MVP]

Dave Sexton said:
The docs recommend using "m_" to prefix private fields.

IIRC, nobody here advocated using the "m". Don't you find that
to be redundant since you're already
using an "_"?

I don't, because we use m_ for instance and g_ for static (at work).
 
J

Jon Skeet [C# MVP]

Those are all good reasons for sticking to the standard conventions for
*public* members, but it's worth noting that as far as I'm aware MS
doesn't have any conventions for *private* members.

Looks like either my memory is wrong or the guidelines have been
updated...

Still, I don't think private naming is nearly as much of an issue (in
terms of cross-community standardisation) as non-private naming.

Now bracing, on the other hand...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top