In praise of ‘_’
Thursday, August 31, 2006 – 8:41 PMI was talking to one of my Developers this afternoon about coding styles. This is one of the things we discussed. It’s something you see a lot, CamelCased properties with associated pascalCased data members.
public
class MyClass
{
private string myName;
This is all well and good but it can lead to some insidious errors like this:
public string MyName
{
set { MyName = value; }
}
Finger trouble means that calling the property setter causes a stack overflow just because of an ‘M’ instead of an ‘m’. This will only happen at run time. It can get worse. In the case below the getter auto initializes the member variable.
public string MyName
{
set { MyName = value; }
get{
myName = (myName ?? “default value”);
return myName;
}
}public void MyMethod()
{
string name = myName;
int len = name.Length;
}
Whereas the setter errors the first time it is executed, MyMethod may succeed depending on the state of myName. If the getter has been called then all is good but if myName is null the code will throw.The author originally intended to use the MyName property so name could never be null but again a typo has led to incorrect code.
To me the following seems much clearer and less prone to weird errors:
public class MyClass
{
public string _myName;
public string MyName
{
set { _myName = value; }
get
{
myName = (myName ?? “default value”);
return myName;
}
} public void MyMethod()
{
string name = MyName;
int len = name.Length;
}
}
In this case prefixing member variables with ‘_’ makes these sort of trivial errors harder to make. It also has the advantage of making it easy to distinguish data members from variables local to a method.
Sorry, comments for this entry are closed at this time.