<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: Circular Dependency in constructors and Dependency Injection</title>
	<atom:link href="http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/feed/" rel="self" type="application/rss+xml" />
	<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/</link>
	<description>Testability Explorer</description>
	<lastBuildDate>Sat, 13 Mar 2010 19:20:13 -0500</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>By: Raghu</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-3161</link>
		<dc:creator>Raghu</dc:creator>
		<pubDate>Fri, 05 Mar 2010 12:05:48 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-3161</guid>
		<description>nice post - came through SO.

I&#039;ve been playing with Apache wicket and ran into this problem. Here&#039;s the scenario:

PageBorder - a border component that wraps around a BasePage and does stuff like setting title, meta etc.

class PageBorder extends Border {
           public PageBorder (id, BasePage page){
                     this.page = page;
                     add (&quot;title&quot;, new Label(&quot;title&quot;, page.getTitle());
           }
}

At the same time, since the BasePage contains the PageBorder, the BasePage needs to know about the border (create the border passing this as a ctor param)
public abstract class BasePage extends Page {
             PageBorder border;
             public add (Component c) {
                       if (border == null) {
                               border = getBorder();
// subclass must create a border passing themselves in
                               add (&quot;border&quot;, border);
                        }
                        border.add(c);
             }
}


In this case, in the BasePage class, I&#039;ve put a protected method - getBorder() - so that the implementing page can decide which border to create.

While this set up works, somehow this seems smelly.

OTOH, if I look at wicket itself, seems like this mutual knowledge is rampant (Page class has a getComponent) and Component classes have a getPage() - however, the coupling is lower.

Any suggestions?</description>
		<content:encoded><![CDATA[<p>nice post &#8211; came through SO.</p>
<p>I&#8217;ve been playing with Apache wicket and ran into this problem. Here&#8217;s the scenario:</p>
<p>PageBorder &#8211; a border component that wraps around a BasePage and does stuff like setting title, meta etc.</p>
<p>class PageBorder extends Border {<br />
           public PageBorder (id, BasePage page){<br />
                     this.page = page;<br />
                     add (&#8221;title&#8221;, new Label(&#8221;title&#8221;, page.getTitle());<br />
           }<br />
}</p>
<p>At the same time, since the BasePage contains the PageBorder, the BasePage needs to know about the border (create the border passing this as a ctor param)<br />
public abstract class BasePage extends Page {<br />
             PageBorder border;<br />
             public add (Component c) {<br />
                       if (border == null) {<br />
                               border = getBorder();<br />
// subclass must create a border passing themselves in<br />
                               add (&#8221;border&#8221;, border);<br />
                        }<br />
                        border.add(c);<br />
             }<br />
}</p>
<p>In this case, in the BasePage class, I&#8217;ve put a protected method &#8211; getBorder() &#8211; so that the implementing page can decide which border to create.</p>
<p>While this set up works, somehow this seems smelly.</p>
<p>OTOH, if I look at wicket itself, seems like this mutual knowledge is rampant (Page class has a getComponent) and Component classes have a getPage() &#8211; however, the coupling is lower.</p>
<p>Any suggestions?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Thomas</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-3074</link>
		<dc:creator>Thomas</dc:creator>
		<pubDate>Sat, 13 Feb 2010 10:56:09 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-3074</guid>
		<description>@Misko,

Well, i was trying to solve that problem since a week :D

I&#039;m waiting for new post/presentation about Oriented Object Concept !

Good luck, and thank you !</description>
		<content:encoded><![CDATA[<p>@Misko,</p>
<p>Well, i was trying to solve that problem since a week <img src='http://misko.hevery.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>I&#8217;m waiting for new post/presentation about Oriented Object Concept !</p>
<p>Good luck, and thank you !</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: misko</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-3064</link>
		<dc:creator>misko</dc:creator>
		<pubDate>Fri, 12 Feb 2010 16:48:41 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-3064</guid>
		<description>@Thomas, 
Glad you figured it out before I get to respond.</description>
		<content:encoded><![CDATA[<p>@Thomas,<br />
Glad you figured it out before I get to respond.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Thomas</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-3063</link>
		<dc:creator>Thomas</dc:creator>
		<pubDate>Fri, 12 Feb 2010 14:47:14 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-3063</guid>
		<description>Hello again :)
Well, I think I have found something ...


class Character {

 private final Client client;
 private final CharStatus status;
 
 // other fields...

 public Character(Client _client, CharStatus _status);

}

public CharStatus {

 private final Client client;
 private int lifePoints;

 public CharStatus(Client _client, int _lifePoint);

 public void fireStatusUpdated(String _property, int _old, int _new); // Using Observer/Observable pattern

}

And finally, class &quot;C&quot; :
class Client {

  public void onStatusUpdate(Client _client, String _property, int _old, int _new);
 
}

The issue was I wanted my collaborator class to send an update to my &quot;super class&quot; Character. Then, my Character send an update to the Client, then Client send data throw network... 

In fact, collaborator classes have to send an update directely to the client...
Circular dependency avoided :)

Sorry for posting !
Thomas.

Ps : I love your job, I think DI is the key for keeping a clean code.
Ps2 : Sorry for ma poor English =) I&#039;m French, and French reputation is to be bad at English ^^</description>
		<content:encoded><![CDATA[<p>Hello again <img src='http://misko.hevery.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Well, I think I have found something &#8230;</p>
<p>class Character {</p>
<p> private final Client client;<br />
 private final CharStatus status;</p>
<p> // other fields&#8230;</p>
<p> public Character(Client _client, CharStatus _status);</p>
<p>}</p>
<p>public CharStatus {</p>
<p> private final Client client;<br />
 private int lifePoints;</p>
<p> public CharStatus(Client _client, int _lifePoint);</p>
<p> public void fireStatusUpdated(String _property, int _old, int _new); // Using Observer/Observable pattern</p>
<p>}</p>
<p>And finally, class &#8220;C&#8221; :<br />
class Client {</p>
<p>  public void onStatusUpdate(Client _client, String _property, int _old, int _new);</p>
<p>}</p>
<p>The issue was I wanted my collaborator class to send an update to my &#8220;super class&#8221; Character. Then, my Character send an update to the Client, then Client send data throw network&#8230; </p>
<p>In fact, collaborator classes have to send an update directely to the client&#8230;<br />
Circular dependency avoided <img src='http://misko.hevery.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Sorry for posting !<br />
Thomas.</p>
<p>Ps : I love your job, I think DI is the key for keeping a clean code.<br />
Ps2 : Sorry for ma poor English =) I&#8217;m French, and French reputation is to be bad at English ^^</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Thomas</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-3057</link>
		<dc:creator>Thomas</dc:creator>
		<pubDate>Thu, 11 Feb 2010 12:57:12 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-3057</guid>
		<description>Hi :)

I have a question about circular dependency...

I have a class Character who is responsible for many and many things : appearance (face, hair...), status (lifepoints...), stats (attack power, defense power...) and i&#039;m stuck !
Look at an example :

class Character {
 private CharAppearance ca;
 private CharStatus status;
 private CharStats stats;

 public Character(CharAppearance _ca, CharStatus _status, CharStats _stats) {
  // 
 }

}

Example of CharStatus :
class CharStatus {

 private int lifePoints;
 private Character owner;
 
 public CharStatus(Character _owner, int _lifePoint) // Here.. circular dependency !

}

How to solve that issue ? Should I remove the owner of CharStatus ? 
Thanks a lot :)
Thomas.</description>
		<content:encoded><![CDATA[<p>Hi <img src='http://misko.hevery.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I have a question about circular dependency&#8230;</p>
<p>I have a class Character who is responsible for many and many things : appearance (face, hair&#8230;), status (lifepoints&#8230;), stats (attack power, defense power&#8230;) and i&#8217;m stuck !<br />
Look at an example :</p>
<p>class Character {<br />
 private CharAppearance ca;<br />
 private CharStatus status;<br />
 private CharStats stats;</p>
<p> public Character(CharAppearance _ca, CharStatus _status, CharStats _stats) {<br />
  //<br />
 }</p>
<p>}</p>
<p>Example of CharStatus :<br />
class CharStatus {</p>
<p> private int lifePoints;<br />
 private Character owner;</p>
<p> public CharStatus(Character _owner, int _lifePoint) // Here.. circular dependency !</p>
<p>}</p>
<p>How to solve that issue ? Should I remove the owner of CharStatus ?<br />
Thanks a lot <img src='http://misko.hevery.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Thomas.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: misko</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-3039</link>
		<dc:creator>misko</dc:creator>
		<pubDate>Sat, 06 Feb 2010 20:43:14 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-3039</guid>
		<description>@Peter,

here is how I would attack you problem.

class Database() implements DB;
class Logger(Database db);
class LoggingDatabase(Logger log, Database db) implements DB;

DB rawDatabase = new Database();
Logger log = new Logger(rowDatabase);
DB dbForTheRestoOfApplication = new LoggingDatabase(log, rowDatabase);

There you go. LoggingDatabase logs the commands as they go by and than delegate it on a class of the same interface. This is know as chain of responsibility and it is my favorite design pattern.</description>
		<content:encoded><![CDATA[<p>@Peter,</p>
<p>here is how I would attack you problem.</p>
<p>class Database() implements DB;<br />
class Logger(Database db);<br />
class LoggingDatabase(Logger log, Database db) implements DB;</p>
<p>DB rawDatabase = new Database();<br />
Logger log = new Logger(rowDatabase);<br />
DB dbForTheRestoOfApplication = new LoggingDatabase(log, rowDatabase);</p>
<p>There you go. LoggingDatabase logs the commands as they go by and than delegate it on a class of the same interface. This is know as chain of responsibility and it is my favorite design pattern.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Peter</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-3037</link>
		<dc:creator>Peter</dc:creator>
		<pubDate>Sat, 06 Feb 2010 04:02:39 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-3037</guid>
		<description>This may be just what i have been after!. 

Can you please help me understand it a little better. 

Lets say i have two classes, a database service for writing to databases and a log service for writing to logs.
I want to pass a logger into the database service via a constructor so that it may the commands.
I also wish to pass a data service into the log service so that it may write the logs to a database.

Can you offer some method of refactoring this such that this is possible?
Secondly i think ive just realised that even if i could instantiate this mess then i will probably end up getting a stack fault when it executes a command, logs it, writes the message to the database, logs about that, logs it, writes a message etc etc.....Perhaps the refactoring will address this too?


public class LogService : ILogService
    {
        private IDataService _data;

        public LogService(IDataService data)
        {
            _data = data;
        }

        #region ILogService Members

        public void Write(string message)
        {
            _data.Execute(string.Format(&quot;prcLogMessage {0}.&quot;, message));
        }

        #endregion

        public override string ToString()
        {
            return string.Format(&quot;Complex Log Service with data provided by {0}.&quot;, _data.ToString());
        }
    }

public class DataService : IDataService
    {
        private ILogService _log;

        public DataService(ILogService log)
        {
            _log = log;
        }

        public void Execute(string command)
        {
            _log.Write(string.Format(&quot;Starting execution: {0}.&quot;, command));
            // Execute command
            _log.Write(string.Format(&quot;Finished executing: {0}&quot;, command));
        }

        public override string ToString()
        {
            return string.Format(&quot;Complex Data Service with logging provided by {0}.&quot;,_log.ToString());
        }
    }</description>
		<content:encoded><![CDATA[<p>This may be just what i have been after!. </p>
<p>Can you please help me understand it a little better. </p>
<p>Lets say i have two classes, a database service for writing to databases and a log service for writing to logs.<br />
I want to pass a logger into the database service via a constructor so that it may the commands.<br />
I also wish to pass a data service into the log service so that it may write the logs to a database.</p>
<p>Can you offer some method of refactoring this such that this is possible?<br />
Secondly i think ive just realised that even if i could instantiate this mess then i will probably end up getting a stack fault when it executes a command, logs it, writes the message to the database, logs about that, logs it, writes a message etc etc&#8230;..Perhaps the refactoring will address this too?</p>
<p>public class LogService : ILogService<br />
    {<br />
        private IDataService _data;</p>
<p>        public LogService(IDataService data)<br />
        {<br />
            _data = data;<br />
        }</p>
<p>        #region ILogService Members</p>
<p>        public void Write(string message)<br />
        {<br />
            _data.Execute(string.Format(&#8221;prcLogMessage {0}.&#8221;, message));<br />
        }</p>
<p>        #endregion</p>
<p>        public override string ToString()<br />
        {<br />
            return string.Format(&#8221;Complex Log Service with data provided by {0}.&#8221;, _data.ToString());<br />
        }<br />
    }</p>
<p>public class DataService : IDataService<br />
    {<br />
        private ILogService _log;</p>
<p>        public DataService(ILogService log)<br />
        {<br />
            _log = log;<br />
        }</p>
<p>        public void Execute(string command)<br />
        {<br />
            _log.Write(string.Format(&#8221;Starting execution: {0}.&#8221;, command));<br />
            // Execute command<br />
            _log.Write(string.Format(&#8221;Finished executing: {0}&#8221;, command));<br />
        }</p>
<p>        public override string ToString()<br />
        {<br />
            return string.Format(&#8221;Complex Data Service with logging provided by {0}.&#8221;,_log.ToString());<br />
        }<br />
    }</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: misko</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-1015</link>
		<dc:creator>misko</dc:creator>
		<pubDate>Tue, 12 May 2009 01:13:21 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-1015</guid>
		<description>@Nigel,

That sounds right. I always have an uneasy feeling whenever I create circular dependency. Sounds like in your case there are some common things you need to pull out to C. I guess the question to ask is why do these two objects need to have circular dependency, on how can we rearrange the responsibility to break it. Without knowing details it is hard to make a suggestion.</description>
		<content:encoded><![CDATA[<p>@Nigel,</p>
<p>That sounds right. I always have an uneasy feeling whenever I create circular dependency. Sounds like in your case there are some common things you need to pull out to C. I guess the question to ask is why do these two objects need to have circular dependency, on how can we rearrange the responsibility to break it. Without knowing details it is hard to make a suggestion.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Nigel</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-1008</link>
		<dc:creator>Nigel</dc:creator>
		<pubDate>Mon, 11 May 2009 09:32:43 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-1008</guid>
		<description>Yes its legacy code :-(
I can&#039;t create an object C (yet) but still want to minimise the effect of the circular dependency. To do that I&#039;ve pulled some of the setter logic up into the factory but this seems to contradict your answer to Q4 in &#039;Flaw-constructor does real work&#039;.
&quot;The responsibility of the factory is to create the object graph and to do no work (All you should see is a whole lot of new keywords and passing around of references). The responsibility of the object graph is to do work, and to do no object instantiation.&quot;
I&#039;ve decoupled the objects enough to get them under test, but now in B&#039;s case the back-reference is set within the object, and in A&#039;s case its set by the factory.
It doesn&#039;t &#039;feel&#039; right but perhaps its just the cost I have to pay until I can create object C. :-)

class A {
  final B b;
  A(){
  }
  setB(B b)
    this.b = b;
  }
}

class B {
  final A a;
  B(A a){
    this.a = a;
  }
}

B createB() {
  A a = new A();
  B b = new B(a); // Sets the backreference internally
  a.setB(b); // Sets the backreference explicitly.
  return b;
}</description>
		<content:encoded><![CDATA[<p>Yes its legacy code <img src='http://misko.hevery.com/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /><br />
I can&#8217;t create an object C (yet) but still want to minimise the effect of the circular dependency. To do that I&#8217;ve pulled some of the setter logic up into the factory but this seems to contradict your answer to Q4 in &#8216;Flaw-constructor does real work&#8217;.<br />
&#8220;The responsibility of the factory is to create the object graph and to do no work (All you should see is a whole lot of new keywords and passing around of references). The responsibility of the object graph is to do work, and to do no object instantiation.&#8221;<br />
I&#8217;ve decoupled the objects enough to get them under test, but now in B&#8217;s case the back-reference is set within the object, and in A&#8217;s case its set by the factory.<br />
It doesn&#8217;t &#8216;feel&#8217; right but perhaps its just the cost I have to pay until I can create object C. <img src='http://misko.hevery.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>class A {<br />
  final B b;<br />
  A(){<br />
  }<br />
  setB(B b)<br />
    this.b = b;<br />
  }<br />
}</p>
<p>class B {<br />
  final A a;<br />
  B(A a){<br />
    this.a = a;<br />
  }<br />
}</p>
<p>B createB() {<br />
  A a = new A();<br />
  B b = new B(a); // Sets the backreference internally<br />
  a.setB(b); // Sets the backreference explicitly.<br />
  return b;<br />
}</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: misko</title>
		<link>http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/comment-page-1/#comment-995</link>
		<dc:creator>misko</dc:creator>
		<pubDate>Sun, 10 May 2009 04:18:41 +0000</pubDate>
		<guid isPermaLink="false">http://misko.hevery.com/?p=146#comment-995</guid>
		<description>@Nigel,

I am sorry, but I don&#039;t understand your question. Can you explain it in more detail. 

In general if I have legacy code and I creating an object is expensive, I first make sure that I can DI the object so that I can  control the instantiation and hence where the cost is incurred. I would than try to pull out an interface so that I can write a mock.</description>
		<content:encoded><![CDATA[<p>@Nigel,</p>
<p>I am sorry, but I don&#8217;t understand your question. Can you explain it in more detail. </p>
<p>In general if I have legacy code and I creating an object is expensive, I first make sure that I can DI the object so that I can  control the instantiation and hence where the cost is incurred. I would than try to pull out an interface so that I can write a mock.</p>
]]></content:encoded>
	</item>
</channel>
</rss>
