Re: Automatic linking of related objects in constructor
Qu0ll wrote:
Suppose you have class A which contains a list of objects of class B and that
the constructor for B takes in a reference to the A object which is to include
it in said list. Is it safe to make a call to A's method addB(B b) in that B
constructor passing in "this"? I have heard that it's bad practice to "leak" a
reference to an object from within its own constructor because it may be in an
invalid state.
If not, how else can I automatically add the B object to the list in A without
forcing the client programmer to explicitly call addB() given that they have
already passed in the B as an argument?
I would have 'A' call its own 'addB( theB )' just after calling 'new B()':
public class A
{
private List<B> daBs = ...;
public void theMethod()
{
daBs.add( new B(this) );
...
}
}
No leakage. The add occurs after construction of the 'B' finishes. You are
correct to worry about leakage. The idiom shown here guarantees that 'B' has
its everything done before the list addition can occur.
--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg