I have a class MyClass:
public class MyClass {
private MyComplexType member1;
}
I have to do some pretty intense initialization on member1. Enough that it easily warrants its own method, called from the MyClass constructor.
My question is, which of the following formats is best for this method?
private MyComplexType initMyComplexType() {
MyComplexType result = new MyComplexType();
// extensive initialization on result...
return result;
}
called like this:
public MyClass() {
member1 = initMember1();
}
OR
private void initMember1() {
member1 = new MyComplexType();
// extensive initialization on member1...
}
called like this:
public MyClass() {
initMember1();
}
Which is the better style for a private member? Why?
I would choose the first option as it more clearly expresses the purpose of the init method and shows the data flow explicitly.
Not to mention that it makes the code in the init method potentially reusable. Should you need to initialize another variable later, you can just call the method again without worrying about side effects. Furthermore, if that other variable is in another class, you can easily move the method to somewhere accessible to both places.
Along this line, I would also consider remaining the init method to something like
doExtensiveComplexCalculationto decouple it from your actual member variable.