Reputation: 3871
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?
Upvotes: 3
Views: 185
Reputation: 89799
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())
Upvotes: 4
Reputation: 13789
Letting the this
reference escape (both the styles in the question) before the constructor completes execution is bad (1) in multi-threaded applications and (2) when the MainClass
gets extended.
Upvotes: 4
Reputation: 65516
Both are acceptable. However you'd use the second if you the new could throw an exception that you can deal with. I recommend the second, as this localises the iniitalisation to one place, and can be called from other constructors too.
Upvotes: 2