Tuesday, March 27, 2007

Coding convention of prefixing instance variables and Java 7's language support for JavaBeans properties

The coding guidelines in our company specifies that all instance variables must be prefixed with 'm'.

I think this is ugly, and if you need this prefix to tell whether a variable is an instance variable or a local variable/parameter, there is a bad code smell that indicates refactoring is needed.

In addition, a good IDE, such as Eclipse and IntelliJ, can display instance variables, static variables and local variables in different colours and styles. (NetBeans's support in this area is disappointing, even in 5.5)

Rod Johnson, Spring's founder, said that he did not advocate this practice in his famous book "Expert one-on-one J2EE Design and Development".

Anyway, this practice will be in conflict with the language support for JavaBeans properties in Java 7:

To declare a simple JavaBeans property, currently you code:
public class Foo {
private Bar baz;
public Bar getBaz() { return baz; }
public void setBaz(Bar newBaz) { this.baz = newBaz; }
}

In Java 7 you'll code:
public class Foo {
public property Bar baz;
}

You only need provide your own getter/setter methods only if you need to overwrite the default.

To access the properties, currently you code:
thisFoo.setBaz(thatFoo.getBaz();

In Java 7 you'll code:
thisFoo->baz = thatFoo->baz;

So you see, if you stick to the prefixing practice, you cannot utilise the new language support for properties.

So I'm in favour of abolishing prefixing instance variables at all. However, depending on the degree of comfort in an organisation, prefixing other variables is still acceptable, such as prefixing class variables with 's' and prefixing local varialbes and method parameters with 'new', 'the', 'tmp', 'old', 'p' or 'l', etc.

No comments: