When the IOC met Node.js

Source: Internet
Author: User

The age of No IOC

A simple example:

var Engine = require ('./engine ');
var Wheel = require ('./wheel ');

var car = function () {
  this.engine = new engine ();
  This.wheel = new Wheel ();
}

Car.prototype.run = function () {
  this.engine.run ();
  This.wheel.run ();
  Console.log (' Run car ... ');
}

Module.exports = car;

In the example, the car needs to rely on wheels (wheel) and the engine (engine) to run. In order to deal with this relationship, it is necessary to first artificially introduce engine and wheel through require, and then instantiate it through the new operation so that the car can really run.

This example is very simple, but there are some problems:

When require, you need to know the file location, filename, and exports of engine and wheel directly. Once a engine or wheel file name, location, exports change occurs, the require operation must be changed accordingly

Car is directly dependent on engine and wheel, so if we try to do unit testing, we find it very difficult to mock engine or wheel, either by modifying the engine, wheel code, or by modifying the car's code

This example has only 3 objects, and the reader may not think it matters much, so it's not a big deal to do directly. But what happens when the number of objects inside the system gets bigger? This may be the case for complex dependencies:

Such systems are tightly coupled, often resulting in difficult to maintain, difficult to refactor, and difficult to do unit testing, especially when a new person joins the team, also because this complexity becomes difficult, can not understand also change.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.