2

In my nodejs project, I have functions like this for socketio.

socket.on('draw', function (data) {
    socket.broadcast.to(socket.room).emit('draw', data);
    addEvent(socket, ["draw", data]);
});

I'd like to rewrite them to something like this:

function onDraw(socket, config) {
    return function (data) {
        socket.broadcast.to(socket.room).emit('draw', data);
        addEvent(socket, ["draw", data]);
    }
}

socket.on('draw', onDraw(socket, config));

The idea is that by placing all of my functions in simple closures like this, I can put them in different modules and it will make it easier to test by passing mockup objects to the function that construct the callback.

I was wondering if it was overkill or if there is a better way to make my code testable?

1 Answer 1

3

IMHO it is not overkill, that is just the Javascript (or functional) form of the command pattern, used in conjunction with dependency injection.

The classic OO equivalent for achieving the same, is to construct a command class, pass socket and config through the constructor, store them in some member variables, and add a member function like Draw(data) using that member variables. That would result in much more boilerplate code - whilst your example is very concise compared to the OO version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.