Seeking a good praxis in the naming of class variables

  • Thread starter Thread starter Gustaf Liljegren
  • Start date Start date
G

Gustaf Liljegren

Here's a small "problem" I often run into. The argument names in the
constructor are usually the same as the those I want to store away as
class variables. This example shows the problem and how I use to solve it:

public class Person
{
private string _name;
private string _age;

public Person(string name, string age)
{
_name = name;
_age = age;
}
}

It's ugly, but the underscore tells me later on that this variable is
global within the class. Another way I used is single-letter argument
names in constructors (not in other methods), like in:

public class Person
{
private string name;
private string age;

public Person(string n, string a)
{
name = n;
age = a;
}
}

This looks cleaner, but it makes it harder to call the constructor (when
you can't remember the acronyms), and the names don't indicate where the
variables are declared. I hope there are other tidy and useful ways I
have overlooked. Please share your's.

Gustaf
 
Gustaf,

Most people use the underscore to denote private fields in a class.
Others don't use it at all. As for your paramteters, there is clear
guidance in the naming guidelines on how to name them (since n and a are not
too descriptive, they are looked down upon).

In the case where your parameter names are the same as your field names,
you can always specify the scope by using "this", like so:

public class Person
{
private string name;
private string age;

public Person(string name, string age)
{
this.name = name;
this.age = age;
}
}

Personally, I like this approach the best.

Hope this helps.
 
Gustaf Liljegren said:
Here's a small "problem" I often run into. The argument names in the
constructor are usually the same as the those I want to store away as
class variables. This example shows the problem and how I use to solve it:

public class Person
{
private string _name;
private string _age;

public Person(string name, string age)
{
_name = name;
_age = age;
}
}
We tend to put underscores AFTER the variable names in function arguments,
and BEFORE them in class member names, so you'd get

public class Person
{
private string _name;
private string _age;
public Person( string name_, string age_ )
{
...
}
}

As a rule, I try to avoid having the name clashes, but in this sort of
example it's not always possible. Whatever you do, make sure you agree with
anyone else you're working with!

Steve
 
Back
Top