Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: markspace <-@.> Newsgroups: comp.lang.java.programmer Subject: Re: Automatic linking of related objects in constructor Date: Wed, 29 Jun 2011 09:17:29 -0700 Organization: A noiseless patient Spider Lines: 35 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 29 Jun 2011 16:17:30 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="5HSAJfqnDjjLFxXZ6WBWEw"; logging-data="30431"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+V/x7iqRgX95Og0nJA+qrT87FLmCUSgfE=" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.18) Gecko/20110616 Thunderbird/3.1.11 In-Reply-To: Cancel-Lock: sha1:Js1fs1tjFCykH7ihBNg+Sb2xdV0= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:5775 On 6/29/2011 2:56 AM, 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. Yes, imo this is correct. It seems that sometimes you have to do it (constructing Swing components) but in general it's a bad idea. > 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 like the factory pattern best here class A { private ArrayList list; private A() {} /** Factory for constructing new A's */ public static A newInstance( B... bs ) { A a = new A(); a.list = new ArrayList(); a.list.addAll( bs ); return a; } }