by jeswin · 12y ago · 0 comments
Dependency Injection is a redundant, useless pattern in dynamic languages; especially when it comes to testability.
In test.js:
//paymentService may be an instance or a class
services.paymentService = mockPaymentService;
....
//use paymentService in your tests here.
The above over-simplified example satisfies most test cases. You can convince me with some use-cases.(Edit: You weren't misrepresenting what I said. Removed that claim. I misread, apology.)
Beyond testing, DI makes it much easier to swap in different implementations of a dependency than simply throwing things into the global scope lets you do. Suppose I want to switch my model from one that communicates with Parse to one that communicates with Firebase. Supposing I adhere to the same interface, I should be able to simply drop it in place without affecting other functions or objects that still rely on the Parse version of the model.
Parse and Firebase example:
//someservice.js
...
//works as long as both retain the same interface.
provider = new FirebaseProvider; //new ParseProvider()
//add: just using an if condition, the old fashioned way.
getProvider: function() {
if (config.provider === 'parse')
return ParseProvider()
else
return FirebaseProvider()
Why is writing configuration cleaner than doing the above? That thought process is carried over from projects with lengthy build time.