node.js - How can I avoid filling my JavaScript code with type-checking logic when using dependency injection? -


i'm trying employ solid principles learnt strongly-typed languages in node.js application, , implement dependency injection through constructor in modules.

without compiler me, i've found myself impulsively writing type-checking , null-reference checking logic make sure dependencies of correct type being passed in.

var _ = require('lodash');  var examplemodule = function(dependencies) {     var app, express, http;      if(_.isundefined(dependencies) || typeof dependencies !== 'object') {         throw new referenceerror('no dependencies object passed constructor. passed: ' + typeof dependencies);     }      if(_.isundefined(dependencies.express)) {         throw new referenceerror('the express module must passed \'express\' property in constructor.');     } else {         express = dependencies.express;     }     // tempted add type check dependencies.express here      if(_.isundefined(dependencies.http)) {         throw new referenceerror('the node http module must passed \'http\' property in constructor.');      } else {        http = dependencies.http;      }     // tempted add type check dependencies.http here  };  module.exports = examplemodule; 

this feels fundamentally wrong 2 reasons

  • constructors filled many conditional statements; increase in size more dependencies needed.
  • many unit tests written check type-checks , null-reference checks working

i don't want spend half time maintaining type-checking logic, don't want spend half time debugging errors when wrong type of dependency passed in.

what design pattern missing solve problem?

small, important clarification: solid "d" not dependency injection. dependency inversion.

for better understanding of solid pertains dynamically typed languages, watch presentation jim weirich: http://confreaks.tv/videos/rubyconf2009-solid-ruby

it's ruby, principles same when applied javascript.

there's own solid javascript presentation did few years ago: https://sub.watchmecode.net/episode/solid-javascript-presentation/

...

your own answer talks require dependency injection, isn't correct.

the require call module loader, not dependency manager. difference subtle, important.

the call require loads code file. not supply dependency other code. have either call code w/ loaded module, or use tool such wire.js supply dependency you.

...

regarding dependency injection question: "it depends" viable answer.

i use type checking this, when dealing internals of applications.

however, if you're building api called third parties, necessary have done, make sure api called correctly.


Comments