HomeBlogProjectsHire me

Creating singletons in node.js

Nodejs modules are singletons

About 2 minutes length

A singleton is a common design pattern in object oriented programming.

This pattern forces the program to have only one instance of an object at a time.

In modern JavaScript and TypeScript, lot of developers could create a singleton writing a class and then exporting a single instance of it.

class Foo {
constructor() {
this.bar = 10;
}
decrement() {
this.bar--;
}
increment() {
this.bar++;
}
}
export default new Foo();

Guess what, you are doing it wrong.

In node.js modules are singleton by nature, so you does not need to write a class to it!

Let's rewrite it again:

let bar = 10;
function decrement() {
bar--;
}
function increment() {
bar++;
}
export default {
bar,
decrement,
increment,
}

Doing this way is simple and you do not have to create a class (and the machine will not have to instance a unused prototype) and you will avoid to create new instance of Foo class.

Other blog posts:

typescripttype guardsclean code

The try/catch and if/else hell

As a functional programming library, tiinvo can help a lot for clean code

Read this story
tiinvofunctional programmingclean codeif elsetry catch

Solving a problem with another one.

What if we are making a great mistake? Finding value where there is some.

Read this story
over-engineeringdevelopmentsuggestions

All my links:

Github

Twitter

Dribbble

Linkedin

Hackdoor.io