This question has a slight emphasis on Java but applies to any OO language. Is it good practice to initialize class variables in their declarations? It seems obviously so to me. It minimizes the risk of silly null pointer exception mistakes.
For example:
class myClass{
private String name = "";// initialize here
public myClass(){
//something
}
}
But in some text books they don't bother to initialize straight away. Which is better? Does it matter?
It totally depends on how the class is intended to be used.
One example would be for value classes, which you might often want to be immutable. Ideally in this case you would set the values in the constructor.
If there are genuinely sensible default values then you can provide these at the point of declaration. It does tend to make it fairly easy to see what is the expected default value. Of course, that doesn't work with final fields (as above), as it's not possible to assign another value.
Another consideration is concerned with the relative merits of constructor or mutator initialization. Using constructor initialization ensures that the instance is never in an inconsistent state, while mutator initialization is often more flexible and provides an easier API.
In the initial remark regarding avoiding
NPE
s, I'd say that's best dealt with by using constructor initialization, along the lines of the code above.This has come up repeatedly on SO, so you should search the site for further opinions.
My suggestion for Java (this only makes sense in certain languages):
If the initial value is fixed for the class, then initialize inline.
If different constructors set different initial values, assign the values in the respective constructor.
In C++11 the situation is somewhat similar.
One case where it is better not to initialise inline is where you have multiple constructors that initialise fields in different ways. It would be inefficient to initialise your field at the declaration and then replace that value with a value passed to a specific constructor later.