Note that there are some explanatory texts on larger screens.

plurals
  1. POAdvantages & Disadvantages of Dependency-Injecting Non-Instantiable Objects
    primarykey
    data
    text
    <p>What, in your opinion, are the advantages and disadvantages of dependency-injecting non-instantiable objects in <strong>JavaScript</strong>?</p> <p>Some context you may want to explore are: </p> <ul> <li><strong>Unit-testing</strong> <ul> <li>Is it worth dep-injecting it? After all, you can overwrite the non-instantiable "static" dependency to a fake object for each test even without dep-injection.</li> </ul></li> <li><strong>Refactoring</strong> <ul> <li>Will it become more difficult to locate &amp; refactor the non-instantiable dependency?</li> </ul></li> <li><strong>Readability</strong> <ul> <li>Which implementation is easier to follow? Is the implicitness or explicitness important to you?</li> </ul></li> <li><strong>File-size</strong></li> </ul> <p><br/></p> <h2>Code</h2> <p>Non-instantiable object:</p> <pre><code>WindowFactory = { buildWindow: function() { return {}; } }; </code></pre> <p>Dependency-Injected:</p> <pre><code>(House = function(windowFactory) { this.windowFactory = windowFactory; }).prototype = { build: function() { var window = this.windowFactory.buildWindow(); } }; var house = new House(WindowFactory); </code></pre> <p>vs. The Non-Dependency-Injected variant:</p> <pre><code>(House = function() { }).prototype = { build: function() { var window = WindowFactory.buildWindow(); } }; var house = new House(); </code></pre> <p><br/></p> <h2>Context</h2> <p>My primary goal is to make the code above testable. I've gotten into a habit of externalizing instantiable dependencies (e.g <code>var window = new Window(); var house = new House(window);</code>). This helps when unit- testing instantiable objects (e.g. <code>House</code>), since instead of the real dependencies (<code>Window</code>) I can instantiate the object with a fake (<code>var fakeWindow = {}; var house = new House(fakeWindow);</code>), and not have to worry about redundantly testing the dependencies while testing my object. (This form of dependency-injection is also useful when testing objects that depend on some data being retrieved via XHR, DOM-events, sessionStorage, or cookie.) </p> <p>Now, when the dependency is an instantiable object itself, the benefits are clear to me; but when the dependency is a non- instantiable object (e.g. WindowFactory in the code above), I have second thoughts about the usefulness. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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