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?
The significant different (in my mind) is that the object under test exposes properties that we want to replace at test time.
var A = function() { /* setup stuff */ };
A.prototype.someFunction = B.someFunction;
A.prototype.methodToTest = function(input) {
var result ={};
result.stuff_I_dont_care_about = this.someFunction();
result.stuff_I_want_to_test = input.; // calculate some stuff with
input
return result;
};