Java Pet Peeves #2:Useless assignments
Boy; am I moaning today :)
So my second pet peeve is unnecessary assignments within Java.
Essentially; all member variables will be assigned to a default value (Object=null, int=0, boolean=false), whilst all local variables will have no initialisation.
Thus, the following two classes will be equivalent:
public class ClassThatUnderstandsHowJavaWorks {
private Object o;
private boolean b;
private int i;
}
public class ClassThatDoesntUnderstandHowJavaWorks {
private Object o = null;
private boolean b = false;
private int i = 0;
}
I have heard the argument that the second form is more explicit. I don't but this because it means every time you write a member variable you need to write extra crud. Every time! It would be far better to educate people once and write neat code, than write bad code over and over.
The other aspect of initialisation is allowing the compiler to help you. For example, if you have a variable which should always be initialised within an if clause, how many people would write:
String message = null;
if (someCondition) {
message = "a message";
} else (someOtherCondition) {
message = "some other message";
}
This code will compile, and work; but will allow the situation for message to be null (if neither condition is used). If the assumption is that one of the two conditions will always be true, the compiler cannot help you.
Remove the initial initialisation and the code won't compile:
String message;
if (someCondition) {
message = "a message";
} else (someOtherCondition) {
message = "some other message";
}
because the compiler will catch the fact that there is a route through your code that will leave message in an uninitialised state. Forcing you to rethink your if condition.
This is a bad habit I picked up from C :)
14 Mar 2006, 08:24
Add a comment
You are not allowed to comment on this entry as it has restricted commenting permissions.