"Everything should be made as simple as possible, but not simpler." - Albert Einstein

Sunday, May 10, 2015

Everyone who is coding with .NET, Java or PHP has heard about dependency injection (DI) or about inverse of control (IoC) or is using special framework which implements IoC/DI pattern. IoC and DI can be considered as synonyms. Recently applications written in JavaScript may consist of thousands of code lines and question may occur “Can dependency injection pattern be used in JavaScript”?

Before answering the question, lets figure out what is dependency injection and what are advantages and disadvantages of it.

Dependency injection is a software design pattern that allows to remove hard-coded dependencies and makes it possible to change them. Dependencies can be injected to the object via the constructor or via defined method or a setter property.

Advantages:

Dependency Injection decreases coupling between an object and its dependency

Dependency injection doesn't require any change in code behaviour, it can be applied an existing code

Dependency injection helps isolate the client from the impact of design changes and defects

Dependency injection allows the system to be reconfigured without changing the existing code

Dependency injection allows concurrent or independent development

Dependency injection allows to make code more maintainable and testable, because dependencies’ impact can be removed by replacing dependencies with mocks or stubs

Disadvantages:

When instantiating type you have to know which dependencies to use

Hides type’s instantiation and dependency resolving logic and if error happens, it can be much harder to figure out what's wrong

It can require to write more lines of codes

It can be slower when instantiating a type with keyword new, it’s related to meta data which has to be used while resolving instance

It’s time to move from theory to practice. Let's take a simple example. In this example we have driver who owns a car and the car can have one engine.

From the first view everything looks OK. This code works. If you don’t need to test it or to change it in the future, this is code is fine. However, this code has some issues, one of which is that dependencies are hard-coded.

We have modified our existing code and it is extensible, but driver’s creation procedure has become more complex. In this case dependency injection container can help us. You can define driver’s details in configuration and when you want to instantiate driver you have to do it using dependency injection resolver. In the example below di4js library is used.

As I mentioned before, that dependency injection may required to write more code as we can see in this example, on the other hand, there is one advantage that configuration is defined in a single place and it can reconfigured without changing the existing code base.

Autowire

If you do not want to define all dependencies manually, there is a solution. You can enable autowired option. If it is enabled for dependency resolver, all type's or instance's dependencies are resolved automatically by names. It may reduce the amount of code necessary to register types and their dependencies. With autowired option enabled you have to register only types. By default autowired is disabled.

Let’s simplify the example in order to show how autowired option works.

One more and the most common scenario is mixed mode. By default you can allow to resolve dependencies automatically but some dependencies can be defined manually. Manually defined dependency has bigger priority.

If you are using different naming convention from the one given in the example it can be overridden easily. For more details read di4js documentation.

List of Dependencies

In some situations you may need to resolve a list of dependencies. To achieve this you have to make multiple registrations for single name.

Let’s modify our previous example and let’s say that driver can own more than one car at the same time which one to drive. Modified class diagram can be found below.

First of all we need to modify driver’s definition. Property ‘car’ has to be renamed to ‘cars’ and additional parameter ‘name’ has to be added to method ‘drive’. Let’s look to our modified source code.

If we invoke method ‘drive’, we will get results which will be printed to console output.

tom.drive('wv');
// Engine with 256 hp has been started…
// Car 'wv' has been started...

Using setter methods instead of properties / fluent interface

There is one more fancy feature. Some objects do not have properties, they have only setter methods and fluent interface. Such scenario with di4js library can be handled too. There is one limitation that these dependencies can not be resolved automatically.

If we resolve driver and invoke its method ‘drive’, we will get the same result as in previous examples.

Child container

In all examples global dependency resolver is used, it’s good for demo purposes and small apps. For bigger apps child dependency resolvers should be created per scope. It allows to get better flexibility and extensibility. Parent can be extended or overridden by child without making an impact on it.
First of all let’s register type in global dependency resolver and then try to resolve registered type by name.

Injection to function or object

There is a situation when instance creation can’t be controlled by dependency injection resolver. This situation may occur when you are adapting dependency injection for legacy code or instances are created by other components which you do not control. There is an option to inject dependencies to object or to function.

The first example demonstrates how dependencies can be injected to the function using parameters’ names.

di.inject(function (car) {
car.start();
});

In the second example an array notation is used to inject dependencies to the function.

di.inject(['car', function (car) {
car.start();
}]);

In the following examples I have demonstrated how to inject dependencies to the function. In following examples I am going to demonstrate how dependencies can be injected to an object.

var car = new Car();
di.inject(car);
car.start();

There is the second method how to inject dependencies to object. You have to provide registration name which has to be used while injecting dependencies.

var car = new Car();
di.inject(car, 'car');
car.start();

AMD

di4js is compatible with asynchronous module definition (AMD) and it can be loaded as ordinal module.

Why di4js?

di4js is lightweight library which is inspired by Unity, Spring, AngularJS and others. di4js advantages are that it is a small library and it’s dedicated to solve a certain problem, thus it’s not a massive framework which tries to cover everything. It also doesn’t depend on other libraries, so it’s easy to embed it to an existing code base.

You may ask why it was created. The answer is simple. A range of libraries have been investigated and none of them satisfied expectations. The goal was to gather various components from various libraries to a single place. Initially it was written for internal purpose but now a decision has been made to share it. Maybe it will be useful for others too.
di4js can be used in projects which are not build on big frameworks such as AngularJS, because big frameworks have built in solution for dependency management. di4js can be useful when you depend on small dedicated libraries.

Usage

di4js library is released under MIT license. It can be used in modern browsers or in other JavaScript runtimes such as Node.js. Library can be installed from various package managers: nuget, npm or Bower.

To install di4js module for Node.js, this command should be used:

npm install di4js

To install di4js for web browser, run the following command:

bower install di4js

In Visual Studio di4js module can be installed using NuGet extension. To install di4js, run the following command in the package manager console.

Final thoughts

At the beginning we asked a question “Can dependency injection pattern be used in JavaScript?”. Now we can answer to that question and say that dependency injection can be easily used and is useful in JavaScript, but project size and complexity always has to be considered. Thus, problem has to be identified and after that corresponding solution has to be chosen. Consequently, we can say that every pattern which is used in other languages can be easily adapted to the JavaScript.

Saturday, June 8, 2013

Introduction

JavaScript (JS) is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. At present JavaScript is becoming a more and more popular language. It was originally implemented as part of web browsers so that client-side scripts may interact with the user, control the browser, but now it can be used to write code for server side (Node.Js) or even can be used in databases to write queries (NoSQL).

JavaScript is a very flexible programming language. It can be easily extended with new features which are used in other programming languages.

As it was mentioned before, JavaScript is a prototype based scripting language. A prototype is an object and every created function automatically gets a prototype property that points to a new blank object. In earlier versions of JavaScript created objects were vulnerable, because they could be modified at any time accidentally or on purpose. In some cases it’s an advantage, but when it comes to writing libraries it is a hude disadvantage.

Situation changed when ECMAScript 5 version was released. It included many cool features, which allow to have flexibilty and create more reliable and steady libraries. It allows to implement open/close principle: “A module should be open for extension but closed for modifications”. It means that if client programmer wants to extend an existing object he must create his own derived object.

How to define a class in JavaScript?

There are no classes in JavaScript, because JavaScript is not a type based language like java or C#. Classes can be emulated in JavaScript. They are useful when you need to write complex applications.

First of all let’s create a class using JavaScript basic features and then optimize the same code with class4jslibrary.

One of most important ECMAScript 5 addition was ‘strict mode’, which actually removes features from the language, making the program simpler and less error-prone. If you want to exploit the full potential of JavaScript, all written code should work in strict mode.

‘use strict’;
// You codes goes here...

In order to create a class, function which will represent a type and will act as constructor of that type should be declared.

var Shape = function () {
this.__x = 0;
this.__y = 0;
};

Now let’s create a prototype for the function. Then the function is instantiated and all properties from prototype are copied to new a instance.

Conclusion

class4js module emulates classes and their related features introducing new sugar syntax. This syntax allows to write less code, to have better code reuse and allows to protect your library from undesirable modifications which can break your code. Another class4jsadvantage is that the library is written in JavaScript and doesn’t have any dependencies, and doesn’t need any extra tools to maintain it. Just include to your project and use it.

Tuesday, February 19, 2013

The first part of the book concentrates on core concepts, including schemaless data models, aggregates, new distribution models, the CAP theorem, and map-reduce. In the second part, the authors explore architectural and design issues associated with implementing NoSQL. They also present realistic use cases that demonstrate NoSQL databases at work and feature representative examples using Riak, MongoDB, Cassandra, and Neo4j.