If I know what a field will be initialized to, should I initialize it in the field, constructor, or receive it as a parameter? I am asking about best practices. All three options effectively provide the same result. I am not considering what is happening behind the scenes, because I think it would be insignificant.
This is a general question for curiosity's sake. I do not have a specific problem with this at the moment, although I have in the past. I will use an ArrayList in the following example, because it is a case where you know what it will be initialized to, and if you end up actually wanting to initialize it to another existing ArrayList, there is no harm by preinitializing it. Or is there?
For example, where should I initialize an ArrayList?
Initialized in Field:
import java.util.ArrayList;
public class Initializer {
private ArrayList<String> arrayList = new ArrayList<String>();
public void addString(String string) {
arrayList.add(string);
}
}
Initialized in Constructor:
import java.util.ArrayList;
public class Initializer {
private ArrayList<String> arrayList;
public Initializer() {
arrayList = new ArrayList<String>();
}
public void addString(String string) {
arrayList.add(string);
}
}
Initialized as Parameter:
import java.util.ArrayList;
public class Initializer {
private ArrayList<String> arrayList;
public Initializer(ArrayList arrayList) {
this.arrayList = arrayList;
}
public void addString(String string) {
arrayList.add(string);
}
}