Skip to content

Instantly share code, notes, and snippets.

@d4rkie
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d4rkie/9544470 to your computer and use it in GitHub Desktop.
Save d4rkie/9544470 to your computer and use it in GitHub Desktop.

Dependency Injections

依存性の注入

???

Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.

http://p.tl/2tgA <-- japanese wiki page

Definition

Dependency injection involves at least three elements:

  • a dependent consumer,
  • a declaration of a component's dependencies, defined as interface contracts,
  • an injector (sometimes referred to as a provider or container) that creates instances of classes that implement a given dependency interface on request.

The dependent object describes what software component it depends on to do its work. The injector decides what concrete classes satisfy the requirements of the dependent object, and provides them to the dependent.

Depencency Injection in JS?

Demo

http://jsfiddle.net/K8KFp/8/

Benefits

One benefit of using the dependency injection approach is the reduction of boilerplate code in the application objects since all work to initialize or set up dependencies is handled by a provider component.

Another benefit is that it offers configuration flexibility because alternative implementations of a given service can be used without recompiling code. This is useful in unit testing, as it is easy to inject a fake implementation of a service into the object being tested by changing the configuration file, or overriding component registrations at run-time.

Furthermore, dependency injection facilitates the writing of testable code.

Disadvantages

  • Dependencies registered in the container are effectively black boxes as regards the rest of the system. This makes it harder to detect and recover from their errors, and may make the system as a whole less reliable.
  • Dependency injection hides the class' dependencies, causing run-time errors instead of compile-time errors when dependencies are missing or incompletely implemented.
  • The dependency injection container makes the code more difficult to maintain, because it becomes unclear when you would be introducing a breaking change.
  • If the dependency is injected at runtime, the performance of the application is reduced.

Questions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment