I'm re-evaluating my thoughts on constructor based dependencies vs setter dependencies in JavaScript. I'm trying to see if the same reasons we avoid setter injection in static language like C# and Java still apply in JavaScript.
In other words, why is this:
var a = new A();
var b = new B();
var c = new C(a, b);
better than this:
var a = new A();
var b = new B();
var c = new C();
c.a = a;
c.b = b;
What are the reasons that you would choose constructor parameters vs setters, and why?
What other options are there for runtime composition of the c
object, so that it can correctly make use of a
and b
? When would you choose those options?
Person
, and I wantfirstName
andlastName
off of it, keeping that in the constructor function helps make it more obvious what the implicit interface (or protocol) is between the dependencies you are passing in, and the class. It also means the rest of the class doesn't need to change if you change it to getfirstName
andlastName
from somewhere else.You can use a service locator pattern. Something like
I would use this if the thing I am instantiating is variable based on environment -- like say a client side i18n translator object where you want a different one based on locale, and a passthrough in a dev environment.
You can also use an IoC container pattern (like angularjs). Some people thing the only reason is for composition during test time, and tests can just monkey patch in js, so why have IoC. I think that the real benefit is that you are giving the wiring up of a complex dependancy graph its own abstraction, and if you don't have this you will basically end up doing it anyways in something called "app.js" or "init.js" anyways. Using a full fledged container means that you are giving that code structure, and not going to have to duplicate various bits when you start running tests. For simple cases it isn't worth it, but for complex cases it is.