如何避免使用dependency injection时使用types检查逻辑填充我的JavaScript代码?

我试图在Node.js应用程序中使用从强types语言学习的SOLID原则,并通过模块中的构造函数实现dependency injection。

没有一个编译器来帮助我,我发现自己冲动地写了types检查和空引用检查逻辑,以确保正确types的依赖关系被传入。

var _ = require('lodash'); var ExampleModule = function(dependencies) { var app, express, http; if(_.isUndefined(dependencies) || typeof dependencies !== 'object') { throw new ReferenceError('No dependencies object passed to the constructor. Actually passed: ' + typeof dependencies); } if(_.isUndefined(dependencies.express)) { throw new ReferenceError('The express module must be passed as the \'express\' property in the constructor.'); } else { express = dependencies.express; } // Tempted to add a type check for dependencies.express here if(_.isUndefined(dependencies.http)) { throw new ReferenceError('The node http module must be passed as the \'http\' property in the constructor.'); } else { http = dependencies.http; } // Tempted to add a type check for dependencies.http here }; module.exports = ExampleModule; 

这种感觉根本错误有两个原因

  • 构造函数充满了许多条件语句; 由于需要更多的依赖性,可能会增加规模。
  • 编写了许多额外的unit testing来检查types检查和空引用检查正在工作

我不想花一半时间来维护types检查逻辑,但是当传入错误types的依赖关系时,我也不想花费一半的时间来debugging错误。

我错过了什么devise模式可以解决这个问题?

小而重要的澄清:SOLID“D”不是dependency injection。 它是依赖倒置。

为了更好地理解与dynamictypes语言相关的SOLID,请观看Jim Weirich的演示文稿: http : //confreaks.tv/videos/rubyconf2009-solid-ruby

这是关于Ruby的,但是所有的原则都适用于JavaScript。

还有我几年前做的我自己的SOLID JavaScript演示文稿: https : //sub.watchmecode.net/episode/solid-javascript-presentation/

你自己的答案说require作为dependency injection,但这是不正确的。

require调用是一个模块加载器,而不是依赖pipe理器。 差别是微妙的,但重要的。

require的调用只能从另一个文件加载代码。 它不提供依赖到你的其他代码。 您必须调用带有加载模块的代码,或者使用其他工具(如wire.js)为您提供依赖关系。

关于你的dependency injection问题:“这要看”是唯一可行的答案。

在处理我的应用程序的内部时,我很less使用这种types检查。

但是,如果您正在构build从第三方调用的API,则通常需要执行您所做的操作,以确保正确调用API。

考虑使用打字稿或stream量 。 这将允许像大多数强types语言一样进行打字检查。

 function typedCheckFunction(x: string): string{ return x } typedCheckFunction(5) // would error at compile time 

由于支持atom ,我更喜欢打字稿,但是他们大都是一样的。