Reader small image

You're reading from  Getting Started with Angular - Second edition - Second Edition

Product typeBook
Published inFeb 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787125278
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Minko Gechev
Minko Gechev
author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev

Right arrow

Why do I need DI?


Let's suppose that we have a Car class that depends on Engine and Transmission classes. How can we implement this system? Let's take a look:

class Engine {...} 

class Transmission {...}
 
class Car { 
  engine; 
  transmission;
 
  constructor() { 
    this.engine = new Engine(); 
    this.transmission = new Transmission(); 
  } 
} 

In the preceding example, we create the dependencies of the Car class inside its constructor. Although it looks simple, it is far from being flexible. Each time we create an instance of the Car class, in its constructor, instances of the same Engine and Transmission classes will be created. This may be problematic because of the following reasons:

  • The Car class gets less testable because we can't test it independently of its engine and transmission dependencies.

  • We couple the Car class with the logic used for the instantiation of its dependencies.

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Getting Started with Angular - Second edition - Second Edition
Published in: Feb 2017Publisher: PacktISBN-13: 9781787125278

Author (1)

author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev