Hi George, in my experience, the dependency-injected model you
describe is almost always better, even in the case of static/non-
instantiable/singleton objects.

The first benefit is obviously that you can mock the dependency. This
is often still valuable for non-instantiable objects, although, as you
note, not as often.

The bigger benefit, though, is that your API makes the dependencies
extremely obvious. This helps users of your library figure out what's
going on and to know what else they need to set up in order to get the
whole system working. In a complex library, it's easy to lose track of
all the things that need to happen before you can actually get things
working. Making all the dependencies a part of your API (rather than
implicit things squirreled away somewhere in your code) makes this
extremely obvious.

I'd say the second item is actually more important because it aids in
programmer understanding. All the unit tests in the world don't mean a
thing if nobody can figure out how to actually use your library
correctly ;)

-Rob


On Mar 21, 3:44 pm, georgecalm <[email protected]> wrote:
> Hi Peter,
>
> You're right, I didn't give much context did I... Here it is:
>
> My primary goal is to make the code above testable. I've gotten into a
> habit of externalizing instantiable dependencies (e.g var window = new
> Window(); var house = new House(window);). This helps when unit-
> testing instantiable objects (e.g. House), since instead of the real
> dependencies (Window) I can instantiate the object with a fake (var
> fakeWindow = {}; var house = new House(fakeWindow);), 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.)
>
> 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. That's the reason I've posted
> the question.
>
> - GC
>
> On Mar 21, 4:06 am, Peter van der Zee <[email protected]> wrote:
>
>
>
> > On Mon, Mar 14, 2011 at 1:12 AM, georgecalm <[email protected]> wrote:
> > > What, in your opinion, are the advantages and disadvantages of
> > > dependency-injecting non-instantiable objects in JavaScript?
>
> > What are you trying to accomplish...?
>
> > One disadvantage is that this is at first glance not obvious :)
>
> > - peter

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to