Wednesday, 4 July 2018

What pattern for creating modules?

So these days I see two major ways of dividing a nodejs app into modules. One is more class oriented:// Controller.js class Controller { constructor(service) { this._service = service; } get(req, res) { this._service.doStuff(); return res; } } module.exports = Controller; // Service.js class Service { constructor(config) { this._config = config; } doStuff() {} } module.exports = Service; // index.js const Controller = require('./Controller'); const Service = require('./Service'); const service = new Service(config); const controller = new Controller(service); app.get('/', controller.get.bind(controller)); Or more of a module exporting functions pattern:// controller.js function get(req, res) { service.doStuff(); return res; } module.exports = { get }; // service.js function doStuff() {} module.exports = { doStuff }; // index.js const controller = require('./controller'); app.get('/', controller.get) Obviously they both have advantages. First one is easy to pick up for most backend devs, classes provide a clear structure and constructor injection allows for injecting different modules (this can also be done with the factory function pattern ofc.). But it can result in a bit more boilerplate and issues with this.Second one is simpler, less prone to this errors and a more “functional” approach. But the direct imports make mocking a bit less flexible, and the structure of loose functions allow for a bit more room to make a mess.What do you guys use/prefer? Ofcourse these are not good or bad, and by no means absolute, there is a lot of in between ways.

Submitted July 04, 2018 at 08:08AM by Aesthetickz

No comments:

Post a Comment