Tuesday, May 17, 2011

Naming Convention–Differentiating field, argument,local variables and constant

Fields, arguments, local variables and constants are variables. It is common to use a variable naming convention to distinguish between fields, arguments, and local variables.

Within the body of a method, all of these types of variables can appear. Many find naming conventions to be a helpful aid in getting a rapid understanding of a method's implementation. These conventions have only one purpose : to pour understanding into the brain of the reader as quickly as possible.

To understand a method, you need to understand its data. An important part of understanding data is understanding where it is defined - as a field, argument, or local variable. Naming conventions which distinguish these cases usually allow the reader to understand an implementation more quickly, since they no longer need to scan the class to determine where items are defined.

Some different styles are :

  • field : _foo, foo_, fFoo, this.foo, m_foo, myFoo
  • argument : aFoo, pFoo
  • local variable : foo
  • constant : FOO_FOO
As well, some use a naming convention for type names, to distinguish between interfaces and regular classes :
  • interface : IFooBar
  • class : FooBar, CFooBar
Note that this 'I' and 'C' convention is fundamentally different from the other conventions mentioned above. This convention is visible to the caller, while the other naming conventions, being confined to the implementation, are not. Also note that class name is generally given on what it represents, and methods into it are named on the behaviour or function they do. Similarly interface name is given on what they add to class.

The example code on this site usually follows these conventions :

  • field : fBlahBlah
  • argument : aFooBar
  • local variable : fooBar
  • constant : FOO_BAR
  • class : FooBar
  • interface : IFooBar

The return value of a method is sometimes given a conventional name as well.

See also Sun's remarks on naming conventions in general.

See Also :

Conventional name for return value
Coding conventions
Avoid basic style errors

No comments:

Post a Comment