Java Reference
In-Depth Information
Even this rule is not consistently applied. For example, H ttp URLC onnection
combines the two styles. Either style is probably acceptable, as long as you
pick a style and stick with it.
Hungarian notation and scope
In the Java community, the debate over the use of Hungarian notation has
been waged for many years. This convention is commonly employed in such
languages as C ++ to provide additional information about a variable. For
example, sCity denotes a variable of a type string named city . For the most
part, Java programmers have avoided Hungarian notation, preferring a sim-
pler style that tends to improve the English readability.
Using Hungarian notation might make sense when you need to clearly
mark the differences between full class attributes and common automatic vari-
ables. Consider listing 9.2 (from Tapash Majumder on the http://www.bitter-
java.com message boards).
Listing 9.2
A common Java bug pattern
The use of an attribute name and an automatic variable name within the same method is a
common Java bug pattern. In this case, if users intend to have the value variable updated, they
will be surprised.
public class SomeClass
{
//
protected int value;
B This “value” is
an attribute.
public int getValue(){
return value;
}
public void setValue(int value) {
this.value = value;
}
// lots of distracting methods here
public void readValueFromDatabase() {
int value = 0;
C This “value” is a
local variable.
// lots of distracting code here
D Which “value”
gets used?
value = getFromTable(tableName);
}
We have an automatic variable and an attribute with the same name. We can
easily confuse the two, leading to errors. Four common conventions can come
into play here, and all have been used with good success.
Search WWH ::




Custom Search