[英]Advantages & Disadvantages of Dependency-Injecting Non-Instantiable Objects
What, in your opinion, are the advantages and disadvantages of dependency-injecting non-instantiable objects in JavaScript ? 您认为JavaScript中依赖项注入非实例化对象的优缺点是什么?
Some context you may want to explore are: 您可能想探索的一些背景是:
Non-instantiable object: 不可实例化的对象:
WindowFactory = {
buildWindow: function() {
return {};
}
};
Dependency-Injected: 依赖注入:
(House = function(windowFactory) {
this.windowFactory = windowFactory;
}).prototype = {
build: function() {
var window = this.windowFactory.buildWindow();
}
};
var house = new House(WindowFactory);
vs. The Non-Dependency-Injected variant: 与非依赖注入变量:
(House = function() {
}).prototype = {
build: function() {
var window = WindowFactory.buildWindow();
}
};
var house = new House();
My primary goal is to make the code above testable. 我的主要目标是使上面的代码可测试。 I've gotten into a habit of externalizing instantiable dependencies (eg
var window = new Window(); var house = new House(window);
). 我已经习惯了将可实例化依赖项外部化(例如,
var window = new Window(); var house = new House(window);
)。 This helps when unit- testing instantiable objects (eg 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. 这在对可初始化对象(例如
House
)进行单元测试时会有所帮助,因为我可以使用伪造的对象( var fakeWindow = {}; var house = new House(fakeWindow);
)来实例化对象,而不是真实的依赖项( Window
var fakeWindow = {}; var house = new House(fakeWindow);
不得不担心在测试我的对象时冗余测试依赖项。 (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.) (这种形式的依赖项注入在测试依赖于通过XHR,DOM事件,sessionStorage或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 (eg WindowFactory in the code above), I have second thoughts about the usefulness.
但是,当依赖项是不可实例化的对象时(例如,上面代码中的WindowFactory),我对有用性有了第二个想法。
If you get some gain in unit-testing, that might be more than enough for me. 如果您在单元测试中有所收获,那对我来说可能绰绰有余。 You'll be able to cleanly test the functionality without depending on global/external state.
您将能够干净地测试功能,而无需依赖于全局/外部状态。 The added bonus then becomes the readability;
然后增加的红利变为可读性; you clearly show which global state/api you depend on in the arguments of your function.
您可以在函数的参数中清楚地显示所依赖的全局状态/ api。
Being able to change the static methods in the setup/teardown of the tests is a workaround for the problem, but I personally find it to be error-prone and a chore doing it. 能够在测试的设置/拆卸中更改静态方法是解决该问题的方法,但我个人认为它容易出错,并且很麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.