Wiring Modules in Node.js: Introduction

in #programming8 years ago (edited)

This is the introduction on a series which aims to summarize chapter 7 in the book Node.js Design Patterns by Mario Cascario. This is my first post on steemit and your feedback is important for my growth, so let me know what you think!

Goal of the Series: Analyze the various approaches for wiring modules and highlight their strengths and weaknesses so that we can rationally choose and mix them together depending on the balance of simplicity, reusability, and extensibility that we want to obtain.

Parts of the Series with Links to Post:

  1. Hardcoded dependency
  2. Dependency Injection
  3. Service locator
  4. Dependency Injection containers

Background

I find it useful to think of modules as the lego blocks that compose repositories of code. Their essence as organizable units of software brings a certain zen to my mind.

Cohesion and Coupling

Cohesion: A measure of the correlation between the functionalities of a component. A module that does only one thing, where all its parts contribute to that one single task has a high cohesion. A lego batman car which was also a bat cave would have low cohesion. Here's a post on stack overflow that helped me grasp the concept.

Coupling: How related are two classes / modules and how dependent they are on each other. Being low coupling would mean that changing something major in one class should not affect the other. If you think about coupling in terms of legos, a lego project that has many easily removable and replaceable parts would have would have low coupling. A star wars battle ship that can't easily be upgraded would have low cohesion.

What to Aim for: The desirable scenario is to have a high cohesion and a low coupling, which usually results in more understandable, reusable, and extensible modules.

Unix Philosophy: building small programs that do one thing, do it well, and compose easily with other programs.

Remember YAGNI (You Aren't Gonna Need It): Don't add functionality until deemed necessary. I like my modules to have broad purposes at first and then add inner modules with more specific purposes as the code grows. I give simple names to broad modules to remind me of their simplistic roots. CRUD is a great example of how simple naming can keep your architecture clean.