Closed. This question is opinion-based。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
                        
                        3年前关闭。
                                                                                            
                
        
我试图在Node.js应用程序中采用从强类型语言中学到的SOLID原理,并通过模块中的构造函数实现依赖项注入。

没有编译器的帮助,我发现自己很冲动地编写类型检查和空引用检查逻辑,以确保传递正确类型的依赖关系。

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;


这根本上是错的,原因有两个


构造函数充满了许多条件语句;由于需要更多的依赖关系,其大小可能会增加。
编写了许多额外的单元测试来检查类型检查和空引用检查是否有效


我不想花一半的时间来维护类型检查逻辑,但是当传入错误类型的依赖项时,我也不想花一半的时间来调试错误。

我缺少哪种设计模式可以解决此问题?

最佳答案

小而重要的说明:SOLID“ D”不是依赖项注入。这是依赖倒置。

为了更好地理解与动态类型语言有关的SOLID,请观看Jim Weirich的以下演示:http://confreaks.tv/videos/rubyconf2009-solid-ruby

它是关于Ruby的,但是所有原理在应用于JavaScript时都是相同的。

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

...

您自己的答案是说require作为依赖项注入,但这是不正确的。

require调用是模块加载器,而不是依赖项管理器。差异是微妙的,但很重要。

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

...

关于依赖注入问题:“取决于”是唯一可行的答案。

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

但是,如果您要构建从第三方调用的API,则通常需要执行已完成的操作,以确保正确调用该API。

07-24 09:49
查看更多