JavaScript Design – Should You Prefer Classes or Singletons in Node.js?

classdesignjavascriptnode.jsobject

This question applies especially to Node.js, but also to JavaScript in general.

I started working on a simple web app in Node.js. I'm relatively new to Node and JavaScript, and come mainly from C# and Java.

In my app, obviously I need objects. In C#, I would create a class and instantiate it to get an object.

In Node.js however, I have two options:

  1. Creating a 'class' in a Node module of it's own, and later requireing and instantiating it (like I would do in C#).
  2. Creating an object in a Node module of it's own, and using it
    later by requireing it directly.

I'm trying to decide what the better approach in general is.

I'm leaning strongly towards approach 1, because it lets me instantiate the desired class anytime I want, instead of using a global singleton.

On the other hand, maybe it feels like the better approach simply because I'm used to it, coming from C#. Possibly I'm just trying to do C# in JS?

So my question would be: in Node and generally in JavaScript, when in need of an object to implement a piece of functionality, should I go with classes or with plain objects?

Best Answer

My insight in this matter might not qualify for a full answer, but I think you are comparing to valid approaches, who's differences aren't a matter of style, but of solving different problems.

If you fear of trying to do C# in Javascript, maybe you should start by questioning a more essential premise of yours:

In my app, obviously I need objects.

More often than not, in Javascript this statement is not as unquestionable as you might think. Probably, if you are considering a singleton as an option, you are just looking for a namespace where you can expose a set of functions. In this case, you could just add these functions to module.exports, which is already an object that acts as the namespace of the module.

This is an interesting read about the many patterns that can be used when designing the interface of a module in Node.js.

Related Topic