Sunday, February 12, 2017

Angular 2 Dependency Injection

What is dependency injection (DI)

Dependency injection is a feature of a dynamic language that we quite often use in JAVA web applications and .NET applications. This feature enables efficient re-use of code and instances thus making the programs more memory efficient and light weight, still at the cost of a few additional lines of code (CPU cycles). This could also in turn provide the programmer with the benefit of design patterns such as Singleton and Factory patterns without having to code them from scratch (We will discover how as we proceed). To conclude what is DI, it's a mean by which we inject an instance of an object (called services in Angular 2) to another Object (mostly to a component) in order to have clean code and reusable code.

Advantages of DI

Improved changeability

Since the object creation is taken away from the components that uses the object, we no longer worry about the object constructor. Which is great if we're to work in large teams, which might bring continuous changes in to services and components, not for DI would require changes at both ends making it difficult to maintain code.

Cleaner code

Using DI makes the code cleaner. This is because we just have to mention the required object and reference name. Programmer can directly use the instance without having to worry about creating the code with a messy set of constructor parameters and so on.

Object Re-use

Most of the Angular 2 UI's are interaction intensive and requires web requests to be sent often. The best example would be us typing in a text box with suggestions flowing seamlessly. If we are to initiate instances of a single service and keep sending requests there might be a race condition and can cause the TCP sockets to overwhelm. Also having concepts like ES7 Observables (Will be discussed in another blog post) which enables the components to observe services rather than update through call backs or promises, would not be useful if we are to replicate objects without a clear purpose. 

An example:
We have a userDataService to fetch the user profile. This update the users profile picture on the UI. If we are use use a separate services each time we update the profile there will be so many objects and all these will be reflected in your RAM usage. Also if there are repeated requests we cannot guarantee which request will be served last, which is the result that will cause the UI to reflect.

DI in action

Sample Service



It is required to use @Injectable() in order to make the injection possible.

Injecting the dependency


This demonstrate the use of the UserManagementService within AuthService. Which is quite simple. Just call the name of the method required to get the task done

Using Singleton and Different instances for DI

Singleton

If we are to use a singleton design pattern using the DI we should add the providers (Which is the injectable object class) within the angular 2 module. This will directly enable the injection of the dependency throughout the module without any clutter.

@NgModule({
    providers: [UserManagementService]
})
export class AppModule {
    ...
}

Non-singleton

If we are to use separate instances over different components we could declare the providers within their individual components

@Component({
    templateUrl: 'events-page.html',
    providers: [PostService]
})
export class EventsPage {
    ...
}









Sunday, February 5, 2017

AngularJS Vs ReactJS(FaceBook)

Overview


Before starting off with the article I'd like to provide some background as to why this article may be important to starting your next project. I have used AngularJS 2 with Ionic 2 in order to develop the Mobile Application for Reforest Sri Lanka which is available at PlayStore. I have been using ReactJS for about 6 months at CAKE LABS (PVT) LTD during my internship where I was able to clearly see pros and cons of the library.

Introduction




As I have mentioned ReactJS is a "library" it is basically a rendering engine. Whose primary focus is to render. It is build around the concept of the Virtual DOM and the component based architecture. When ever a change happens the Virtual DOM is completely rendered whilst only the tags having a net difference in the Real DOM are then updated. As the mechanism implies all the HTML tags are indexed by the library by injecting them with ID parameters, making it impossible for you to add ID's or rather unconventional if you do so. Due to the component based architecture this enables the reuse of components which makes the development quite easy. At the same time the framework uses JSX (Java Script XML) syntax which seems to be HTML but are not. Thus the styling of the component becomes a not so simple task in the right React way.




Angular JS is actually a framework which  provides all the required libraries off the shelf. This makes the development easy and at a mature level, this makes the size of the minified UI to be reasonably smaller in size since we are reusing the functions provided by the framework itself without having to install third party libraries such as Fetch, Isomorphic Fetch or request handling libraries such as JSONP. All the features are documented in the official website, which was quite not stable until recent. AngularJS 2 also comes with the component based architecture which makes the reuse of components possible but as not simple as in the case of ReactJS. I'd rather like to say its bit messy and not so straightforward with the concept of directives and modules.

Feature Comparison



Angular JS 2 React JS
Use the HTML DOM straightaway Uses a virtual DOM then updating the real DOM
Uses dependency injection model and some ECMA Script 7 features Still in ES 6
Uses components and modules Uses components
HTML/CSS styling can be applied straightaway Needs to use additional libraries such as Radium in order to reuse styles
Can use inline styles which is quite difficult
Styles are provided in the form of JSON objects since we use JSX



When to use what


This quite not straight forward. If the system is so large and there are components that are being heavily re used, the ReactJS might help. Still there might be many additional libraries required in order to handle the Data Architecture (Discussed later in a separate blog) such as Redux/Relay/Reflux. On the other hand the development effort of the React JS framework will be quite high since it is heavily typed and the task of the UI engineer is not just to style but he/she will have to consider the logic in a component. For an example simple expand collapse might require a change in the logic. See the below example.

Class Component1 extends React.Component {
    this.state = { menuOpen: true };

    hanldeOpenClick() { this.setState({ menuOpen: !this.state.menuOpen }); }

    ....

    render() { return <div style={{ LOGIC }}> <MENU_TO_OPEN/> </div> }

}

This would just be handled with CSS or with a lesser number of lines of code in Angular JS 2.

In the template

<div class="{ open ? 'open' : 'close' }">
    <MenuComponent></MenuComponent>
</div>

In the component class

export class ComplaintCard { 
    open: boolean;
    constructor() { this.open = false; } 
    openMenu() { this.open = !this.open } 
}

This might look quite simple but in React render its completely JS and in Angular template its pure HTML. With my experience Angular 2 did a great Job in the ionic application and ReactJS was OK at my internship, yet we had to go through difficulties when including external render component such as maps, color pickers and etc. We had to use raw HTML injections which was not quite a good thing in the library perspective, but after all served the purpose. It shall be noted that React Native and Angular JS with Ionic 2 are completely two different entities which are orthogonal to each other in fundamental terms.

Conclusion


If the system consists of a large number of Components that can be reused, and heavily interactive React JS is the choice. If the system is modular, with several big components, yet of lesser number of reusable entities Angular JS would be fine. Learning curve for React JS is lesser but the development effort will be greater. It also requires a full stack developer with good knowledge in JS + HTML + CSS to get the full use of it which can be easily segregated with Angular JS 2.