Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use classes for Nodejs Models and controller

Is it a good Idea to use classes for controller and Models in Nodejs?

If so, it is better to use one Class instance for all request or use one per request, like Laravel does? Of course Node is different. I think one would be better but I am not sure.

About if using classes, performance is priority.

like image 597
Ángel Barrios Avatar asked Mar 24 '18 21:03

Ángel Barrios


People also ask

Should I use classes in Nodejs?

Lots of people don't know it, but you can use and extend real classes in Node. js already. There's a few drawbacks, but once you learn about them, they're really not drawbacks but postive things, that will make your code faster and better.

For which node JS is not recommended?

js receives a CPU bound task: Whenever a heavy request comes to the event loop, Node. js would set all the CPU available to process it first, and then answer other requests queued. That results in slow processing and overall delay in the event loop, which is why Node. js is not recommended for heavy computation.

Is it necessary to learn express for Node JS?

No, It isn't, ExpressJs is framework build on top of nodejs, as they are many framework in different programming language it is the same for Javascript in the backend side.


1 Answers

Quoting this stackoverflow issue

However, it's important to understand that OOP is very effective for things that can be modeled naturally with it, and is very ineffective for other things (e.g., crosscutting concerns or aspects).

Models are naturally modeled into classes, but Controllers are not.

Controllers

If you use express, it make sense to code routes using functional-programming, and this is the middleware-chaining coding idiom.

You can check also Sails.js, (Sails.js is a MVC express framework) Controllers implementation are not classes, but Models are.

Instanciation

If you have one Class instance for multiple requests, you will have the possiblity to share the access of the instance's scope (this) between multiples requests.

It is cleaner to use one Class instance per request, and to not share memory/scope between your requests.

When you scale up your server (add multiple instances), all requests will be handled in parallel, so you should not share any data between different requests on same nodejs thread.

If you need to share any memory across your requests, it means that you need to put this memory into a separated database, on a separated server.

About if using classes, performance is priority.

This choice is more about readability on my point of view. There won't be much performance difference and you should take care of premature optimization.

If your code is readable it will be easy to rework, and easy to study performance bottlenecks.

like image 184
piercus Avatar answered Nov 15 '22 05:11

piercus