Is it OK to reference this when initializing a field?
public class MainClass {
private SomeFieldClass field = new SomeFieldClass(this);
public MainClass() {}
}
Or is it better to do that in constructor?
public class MainClass {
private SomeFieldClass field;
public MainClass() {
this.field = new SomeFieldClass(this);
}
}
What is the best practice? I believe first option is better for unit testing and dependency injection. Are there any problems with it?
The question is a little unclear. Are you worried about passing this to your constructor, or about using this.field in the constructor body, or about initializing a field in the constructor rather than in the class body?
I personally prefer to use the this prefix when referring to class members, but that is a question of style.
I also prefer not to do initializations of non-constants in the class body. I find that for longer classes, it is better to have all the initializations in one set location (such as the constructor) rather than have to visually scan the declarations to identify the initial values.
If you’re asking about passing this early (an issue in both examples), I feel that it depends on whether you can deal with the possibility of the target doing something with a partially-initialized object. I prefer to separate such creations to a different and explicitly invoked functions (e.g., a createAssociatedSomeObject())