jeudi 9 avril 2020

When to use require and when to provide dependencies through arguments

I've been wondering what is the preferred way of injecting dependencies in node.js code.

I've been working on a project where there is no dependency injection. This is why i have 2 ways of providing dependencies in my code:

Through constructor/function arguments - this has the disadvantage of exploding the number of arguments in functions as i pass arguments from higher levels of my program to the lower ones,

function createListener(queue) {
    return function listen() {
        while (true) {
            const messages = queue.receiveMessages();
            ...
        }
    };
}

Using require() - this is equivalent to hardcoding those dependencies making if harder to mock and test. const queue = require('./queue');

function createListener() {
    return function listen() {
        while (true) {
            const messages = queue.receiveMessages();
            ...
        }
    };
}

I've been trying to hit a sweet spot between those. When providing a dependency which is a complex mechanism i tend to inject it, when dealing with values or less crucial mechanisms i use require.

Is that ok? What would be a better approach?

Aucun commentaire:

Enregistrer un commentaire