Note that there are some explanatory texts on larger screens.

plurals
  1. POWhere to put needed initialization code when using Dependency Injection?
    text
    copied!<p>When my constructors are pure arguments-to-propeties setters then I'm not sure where to put other code that a class needs to properly work.</p> <p>For example in JavaScript I'm programming a <code>WindowMessageController</code> that processes <code>message</code> events on the <code>window</code> object.</p> <p>In order for this to work, I must somewhere attach the handler:</p> <pre><code>var controller = this; this.applicableWindow.addEventListener("message", function(event) { controller.messageAction(event.data); } </code></pre> <p><strong>Where does this stuff correctly belongs?</strong></p> <ol> <li>in the constructor</li> <li>in the .initialize() method - introduces temporal coupling</li> <li>in the WindowMessageControllerFactory.create(applicableWindow) - quite a distant place for so central piece of code. This means that even such a small class would be split into two pieces.</li> <li>in the composition root itself - this would multiply its size when doing all the time</li> <li>in some other class WindowMessageRouter that would have only one method, the constructor, with this code</li> </ol> <p><strong>EDIT</strong></p> <p>This case seems special because there is usually only one instance of such a controller in an app. However in more generalized case what would be the answer if I was creating an instances of <code>Button</code> class that would wrap over some DOM <code>&lt;button /&gt;</code> element? Suddeny a </p> <pre><code>button = buttonFactory.create(domButtonEl); </code></pre> <p>seems much more useful.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload