Tuesday, October 30, 2018

JTD-DesignerSeries-9-NodeJS-101


Let's set some context
Web frameworks enables client-server architecture and Internet is a based on this client server model of computing. Usually there is a web server that listens for http request and the usual client is the browser like chrome. Every browser embeds a Javascript engine, and chrome is a C++ program which embeds Google V8 Javascript engine & makes available extra features like DOM manipulation through Ajax. Web Server, on the other hand, can support multiple technology stack like PHP, C#, Ruby & NodeJS. With NodeJS, you are writing code in Javascript and can share & use same libraries on the client & server side.

What is NodeJS
NodeJS is a server side technology and is a framework built with C++ & Javascript that adds features to the V8 runtime. NodeJS implements common traits of server side technology by wrapping C++ core implementation with Javascript wrappers.

Modules
a) Modules allows Node to organize code in reusable features with the help of require & module.exports constructs. Let's take a example and understand little bit.
app.js
var greet = require('./greet')
greet();

greet.js
var greet = function() {
console.log('Hello');
}
module.exports = greet;

In node implementation of require function, a module object is created, and a wrapper function on the module object passes the JS code to V8 runtime. During the execution of our code, a reference to greet function is assigned to module.exports which is returned from by the require function.This way, the greet function is exposed outside of the module.

b) When module is defined using multiple JS files, all files are placed in a folder and folder name is passed as parameter to the require function. Node will then check for index.js file in the folder which can require the modules defined in the folder.

EventEmitter
a) Event Emitter is a node module that allows you to register several listener functions associated with the event type. When an eventType is emitted, node invokes all listener functions listening for the eventType.

b) An object can inherit from the EventEmitter and then have access to the emit & on functions. Callbacks is a pattern with which you pass first class function and ask the function to invoke a callback after executing its code. Node uses an Event Loop outside V8 and enables developer to implement asynchronous behavior with EventEmitter, Callbacks & Event Loop.

File & fs
var fs = require('fs');
var readFile = fs.readfile (filename, function (err, data) {
console.log(data)
});
a) Node interfaces with the OS functions to read the data from the filesystem in an asynchronous way, and with the event loop check, it initiates a callback with the file data.

var readable = fs.createReadStream(readFilename);
var writeable = fs.createWriteStream(writeFilename);
readable.pipe(writeable);

b) With large datasets, file module provides streams that allows to read the file data in chunks and then use the pipe feature to push it to the writable stream.


Node being a Web Server
var http = require('http');
http.createServer(function(req, res) {res.writeHead(200, {'Content-Type': 'text/plain'}); res.send('Hello World\n');}).listen('3000', localhost);
a) Node abstracts the TCP/IP implementation & really simplifies the creation of a web server. It uses modules like http that require other _http modules along with Node C library (http_parser) and creates a listener on the socket. It then parses the request send by the browser in the req object & provide methods to create a response stream that maps to the standard http status code & mime-types.

b) Express is a node module that provides an easy abstraction to create the web server, enables robust routing features to handle http requests & create http responses. It also supports use of middleware that eases the features between request & response processing.

c) Template is a approach of inserting filler text along with static content in web pages, and during the web page rendering, template engine can process the filler text to generate dynamic content. Express supports quite a few template engines like Jade, EJS.

d) NodeJS makes it easy to with work with relational DB (MySQL) as well No SQL DB (MongoDB) with modules like mysql & mongoose. For eg: mysql node package transforms the resultset into an array of Javascript objects. Similarly mongoose node package provides allows you to define the structure of document with JSON & Schema function, and also provides the driver methods to retrieve & save data to MongoDB.


What is MEAN stack
Web Application is a combination of client side code, server side code, database system & bunch of other glue that connects everything to everything. MEAN stack provides the full stack features by allowing you to develop all these pieces of the App with MongoDB (M), Express (E), Angular(A) & NodeJS (N).
a) MongoDB - Is a NoSQL database technology that allows you to store data in the form of collections & documents.
b) Express - Is a Javascript framework that simplifies creating APIs, Routing by providing a middleware layer on top of NodeJS.
c) AngularJS - Is a Javascript framework that helps you manage the client side UI in the browser.
d) NodeJS - Is a Javascript server that helps you abstract the creation of http server, handling of requests & responses and also enable other server side technologies.

Code Examples
I) Render a index page with "hello" by running an express app on NodeJS.

In the example run we can see that browser renders the html body send by express app running on NodeJS server.

[DS-NodeJS-101-HelloWithNodeAndExpress]:https://github.com/madajee/JTD-DesignerSeries-9-NodeJS-101.git

II) Angular App rendering the Hello message returned from Node & Express App.

[DS-NodeJS-101-HelloWithAngularNodeAndExpress]:https://github.com/madajee/JTD-DesignerSeries-9-NodeJS-101.git
In the example run we can see that browser renders the he value of the message variable [Hello With Angular, Node & Express] defined in server side app.js file.


Todo Basic App with MEAN
Application [node-todo]: Let's build a To-Do list app with a MEAN stack.
[DS-NodeJS-101-TODO-MEAN]:https://github.com/madajee/JTD-DesignerSeries-9-NodeJS-101.git


Links & References
a) Learn & Understand NodeJS by Anthony Alicia on Udemy

Tuesday, October 2, 2018

JTD-DesignerSeries-9-JavaSkills-101


Let's set some context
I have usually worked in an integration layer and used DSL, but I must agree that direct manipulation of C pointers are extremely difficult and one must understand data structures & algorithms to play with it. However as engineers we all study about it search & sorting on maps & lists.

Languages like C++ & Java support Object Oriented Design with objects modeling provides another layer of abstraction to database relationships. Java popularized Object Oriented Design by supporting platform compatibility with a intermediary layer of Interpreters.

Frameworks like Java EE & Spring have been developed by Java community to support development of complex enterprise applications.

Preliminary Java

a) A developer can use 8 primitive types [byte, short, int, long, float, double, char, boolean] to create variables and 9 one is String which is treated as primitive data type but is really a class.

b) Java is an object oriented language and allows designers to model the data layer with real world objects as classes by applying principles of Abstraction, Encapsulation, Inheritance & Polymorphism.

c) OOPs support Abstraction by blueprinting with class definition & creating objects as instances of class in method implementations. Encapsulation is is managed by defining state with private fields along with getters & setters & behaviors with public methods.

d) Inheritance is a OOPs principle which allows you to define common state & behaviors in base class [Generalization] which are accessible automatically in derived class [Specialization] created by extending from base class.

e) Polymorphism is another OOPs concept which helps Java runtime to dynamically invoke a method implementation depending upon the subclass reference assigned to the base class variable.


f) Arrays allocate memory space for storing fixed number of same data type and each element can be accessed by an index. ArrayList are dynamic arrays which allocates as the elements are added to the ordered list.

g) Java use interfaces to standardize the behaviors and classes can implement multiple interfaces. Abstract classes not only standardize common base behavior which can be implemented in derived but also provides standard implementation of base methods.



h) Java Collection Framework simplifies working on complex functions of searching, sorting by providing interfaces [List, Set, Queue] and classes [ArrayList, LinkedList, Stack] and Generics allows compiler to check collection objects with declared parameterized types.


j) Map Interface, though not really defined in Collection hierarchy provides a container of objects mapped with unique key and uses get & put method to add & retrieve key value pairs from collection classes.

h) Exception happens when something goes wrong in the normal processing. Java compiler is responsible for marking checked exceptions. Developers can then either use throw to delegate exception handling to calling program, or use try / catch for generic handling, or try with multiple catches for specific handling.


i) Unchecked exceptions are direct subclass of Runtime exceptions and it is developer responsibility to handle them as unchecked exceptions like Nullpointer, ArrayIndexOutOfBound are not checked by compiler.



Preliminary Spring

a) Most scalable Java applications are designed using separation of concern design principle & implemented with layered architecture [Data Access Layer--->Service Layer---->Presentation Layer].


b) Designers also use loose coupling by developing with Interfaces & use factory pattern to initialize the dependent objects, and use proxy implementation to enable cross cutting concerns like cacheing, transactions, logging.

c) Rod Johnson developed Spring framework by implementing a BeanFactory which allows developers to manage dependencies & cross cutting concerns with xml configuration & annotations. Factory relies on pattern like Inversion of Control which uses Reflection API to manage a bean lifecycle.


d) An important term in spring application is bean configuration file, which lists the POJO that implement the application features as well as their dependencies. Usually environment specific properties like database urls, tuning parameters, authentication are externalized in properties file rather than hard coded in bean definition.

e) Beans in configuration file are usually assigned an ID & bean dependencies are managed in different ways, either constructor or setters. Spring modules also support Bean Inheritance & Spring Expression Language to support reusability & dynamic assignments.