Skip to main content

Class variable names

Posted by malcolmdavis on August 26, 2004 at 9:14 AM PDT

In "Code Complete" section 9.4 informal naming conventions, Steve McConnell describes the use of module variable 'm_'. Since reading this in 1994, I have used the 'm_' convention in C programs, then C++. I've seen 'm_' used in MFC, and in coding standards for the commercial software companies.

Even though Sun does not explicitly define class variable declaration in the coding standards, much of Sun's code aligns parameter names to an existing field with the same name. Much of Sun's code uses 'this.' to set member variables.

public void setName(String name) {
    this.name = name;
}

I asked Steve McConnell his opinion about 'm_' versus 'this.'. The following is his response:

...

"In general, I'm not crazy about differentiating parameters from member variables solely through use of "this.". I would rather see unique names for all variables. I think you're inviting problems and making the code harder to figure out if you name everything exactly the same. I'm not wedded to the "m_" prefix specifically, but I'd like to see the member names and parameter names be unique through some technique or other."

...

Some people use the underscore '_' to determine a variable's scope, such as Docman at SourceForge. Hence, the above sample would be:

public void setName(String name) {
    _name = name;
}

I've also know people to use 'p_' for differentiating parameters, as shown to the following sample:

public void setName(String p_name) {
    m_name = p_name;
}

C# has a different twist by providing a 'property' feature: (note the implied 'value')

public string Name {
    get {  return name;  }
    set {  name = value; }
}

Even though the C# 'property' feature looks good on paper, in practice the feature is widely misused.

The software language scene will change a great deal over the next few years with the arrival of meta information, aspect oriented programming, code generation integration, and new programming features like C# properties. However, I think at this point, it is still important to differentiate the scope of variables. Even though it looks Hungarian in nature, the focus of Hungarian notation is to identify the type of a variable, not the scope. The issue with Hungarian is that the classical types did not fall into the Object-Oriented world, and types very often change.

Related Topics >>