The point of instance variables is to store the state of the class. It should not be used as a shortcut to shorten method signatures:
private String var;
public Constructor() {
var = "Foo";
... //perhaps var was modified, perhaps not
printVar();
}private void printVar() {
System.out.println(var);
}You should use this instead:
public Constructor() {
String var = "Foo";
... //perhaps var was modified, perhaps not
printVar(var);
}private void printVar(String var) {
System.out.println(var);
}Imagine you had to debug a problem in printVar. In the first example, all code in the class is suspect. var could have been modified anywhere
throughout the class to cause the bug. In the second example, only the methods related to the call of the printVar are suspect.
There is a situation where the first example, with a little modification, is acceptable. If var was final, immutable and used all over the place,
printVar could be implemented the way it is in the first example. Since Strings are immutable, the first example would look like this:
private final String var;
public Constructor() {
var = "Foo";
... //var is not modified
printVar();
}... //many more uses of printVar()
private void printVar() {
System.out.println(var);
}don_t_use_instance_variables_to_shorten_method_signatures, Rev. 5, Last changed on 2008-01-10 00:43, 166 page hits