Warning: Leaking "this" in constructor
I keep running into this, and I have a nagging feeling that it's because my design is wrong or not optimal.
I understand that this warning is bringing to my attention the fact that I am allowing access to an object that is potentially not fully initialized.
Let's say that I need a Frame that HAS and requires a List (Frame(List list)). In List, I might want to do something such as add(). In order to make sure Frame knows as little about List as possible (only that it has one), I would want to access the containing Frame from the List (List HAS a Frame?). This seems a little silly, but I have 2+ implementations of List that will use Frame in different ways..
To ensure that my code is used properly, I would require a Frame in the constructor of List. I would also require a List in the constructor of Frame, as it MUST have one:
public abstract class Frame {
private final List list;
public Frame(List list) {
this.list = list;
list.setFrame(this);
}
}
public abstract class List {
private Frame frame;
protected final void setFrame(Frame frame) {
this.frame = frame;
}
}
So, is this bad design, or should I really create some intermediate scaffolding that does this, or even leave the scaffolding to the user?
Thanks!
I think that this sort of "doubly linked" structure, where a Frame points to a List that points back to its parent Frame, is something you ought to avoid unless you have a specific need for it. You should if possible try and make one of the two objects the "parent" that points to the "child."
It's a bit hard to understand at first why the double-linking is not such a great idea, but here are some reasons:
This is not to say that the double-linked structures are never appropriate, but rather that the simpler, single-linked structures should probably be the first choice.
Introduce a factory method:
This does not leak this, and always makes sure everything is configured correctly without the need for every caller to remember initializing both sides of the association.