Saturday, July 23, 2016

Javascript is one of the 3 main core technologies in world wide web. Since it's origin 2 decades back, it has evolved a lot and as per today, it is the trendiest programming language on earth.

Since 2009 I have used javascript to do web development and until recently I used it with basic dom manipulations with jquery, simple UI logic with vanilla JS and with some frameworks as AnuglarJS. The basic knowledge I had about JS was sufficient enough to get above things done. But recently when I started doing some serious development with React and GraphQL, I realized that my knowledge on JS is pretty primitive and I'm not really applying any core JS concepts or patterns in my code. At the same time, while I was listing to a podcast in Software Engineering Daily I found Kyle Simpson was explaining about series of his books called "You Don't know Javascript". With that, I got the interest in reading the book to sharpen my saw in JS. It's a pretty interesting book and it covers many basic concepts in JS. Following series of articles will cover what I learned in each of these books.

Scope

The scope is one of the core concepts in Javascript and it's a must to have a thorough understanding of the scope to write better JS code. Let's dig in further to scope.

What is scope?

The scope is set of well-defined rules on how to store and retrieve variables in a program. In one way or other, you are always dealing with these rules when writing and execute code in JS.

In JS assignment for the scope can be performed in two ways.

1) by using = expression

a =3;

2) or by passing an argument to a function parameter.

function foo(x) {
}
foo(3);

Lexical Scope

In JS, the scope is defined by Lexical Scope. Lexical Scope is defining the scope at author time based on where the functions are placed.

But there are two other ways to overwrite the lexical scope in JS. Those are JS core functions which will manipulate the scope at runtime. Those are,

1) eval() function

Eval function takes a string as an input and executes the content in the scope of the code execution.2) with() functionTakes an object as the input and consider the object as a new separate lexical scope.

In JS we can define different levels of scopes. The most outer scope is global scope and new scopes will be defined as nested scopes when we are creating functions or blocks.

var a =5;
function foo(x) {
var b =10;
}

In above example "a" is in global scope and "b" is in a new function scope.

When Javascript engine finds a variable in an inner scope engine starts searching for it in the given scope and if it isn't there, it checks the variable in the immediate outer scope and likewise it traverse until it finds the variable and returns it. Once it reaches the most outer scope, it automatically stops traversing.

There is a really tricky part in how the fall back happens when the engine cannot find a defined variable in any given scope. If a variable is not found in any parent scope and if it's for an assignment purpose, then a new variable will be created in the global scope. You should be really careful on this.

var a =5;
function foo(x) {
b =10;
}

When Javascript engine finds a variable in an inner scope engine starts searching for it in the given scope and if it isn't there, it checks the variable in the immediate outer scope and likewise it traverse until it finds the variable and returns it. Once it reaches the most outer scope, it automatically stops traversing.

Note: Global variables are automatically being part of the global object. In browser, it's the window object. So you can create global variables as "window.a". Using this technique you can access the variables in the global scope without getting affected from shadowing. Ex:

There is another interesting point demonstrated in the above example. It's shadowing.

Shadowing

Overriding the outer scope variables in inner scopes. Shadowing is commonly used in JS which allows developers to isolate variables within functions while using same variable names.

Since scope is really powerful as well as dangerous when misusing it, there are identified best practices to avoid surprises. All these best practices are targeting common objectives such as avoiding spoiling global scope, isolate variables in function scope as much as possible. Following are some of such best practices.

Isolate in objects

It's a best practice to create an object in the global namespace and define variables and functions as properties of the object. In this way, we will only define a limited number of variables in the global scope and all the other variables will be properties of carrier objects.

Most of the modern JS libraries wraps its variables in a module and expose via dependency management. When using these libraries in code, we have to import scope into another object scope which will prevent spoiling the global scope.

Will be covered more under Closure section.

Functions as Scope

When we have named functions, it pollutes the global name space. That can be avoided with following technique by treating function as an expression rather than a declaration.

This is a great way to keep the global scope clean as well expose necessary components to outside while maintaining an internal state of the module.

Now we have come to the end of this article about Javascript Scope and Closure concepts. Hope you got some quick interesting points about them and if you need further readings it's highly recommend to read the series of "You Don't know Javascript" books. I'll bring some more interesting points in my next article about Javascript Objects and Prototyping.

Wednesday, July 13, 2016

Rest is the underline architecture of Web and how the clients and servers communicate each other. Using Rest, clients and servers can communicate each other without a prior knowledge. Because of the power of Rest principles, over the time software architects have grabbed the core principles from it to implement APIs in applications. Following are some of the core principles in Restful APIs.

It works over HTTP protocol which is stateless

The architecture fully operates with the concept of individual Resources which are identified uniquely through URIs.

Resources can be manipulated using basic HTTP verbs such as GET, PUT, PATCH...

Since Restful APIs fully focused on individual resources, there are several consequences you'll face other than all the advantages you are getting with Restful APIs.

Since the resource manipulation is done through HTTP verbs, the ability to perform complex manipulations containing multiple different types of resources is not straightforward. There may be situations where clients needed to have multiple roundtrips to perform such an operation.

In order to manipulate multiple related resources, clients will have to maintain the state between operations through headers or other way.

Service discovery and client tooling will be difficult due to lack of a strong type system at back end.

Since resource representation should be generic at the API and all the clients will share the same representation, there won't be any control on the amount of transfer data to clients(over fetching).

When it comes to mobile clients, the disadvantages such as multiple roundtrips, over fetching data will be really critical because those are used in low bandwidth environments.

When Facebook has started their mobile apps in 2012, initially they have decided to use a Restful API to communicate with backend services. With drastic development cycles, they have found that many versions of their mobile app are out there in use(one in each two weeks) which calls to the same backend service runs on Rest architecture. This has lead to serious issues on managing and maintaining their API to support different versions of the client apps. A set of engineers at facebook have started to find a new way of overcoming these problems and GraphQL has come out as a result of that effort.

What is GraphQL?

A data query language for client applications defines a flexible way to request and provide data requirements. It allows developers to define the data requirement as same as they think about the data.

Following are some of the main advantages in GraphQL over Restful APIs.

Hierarchical: Most product development today involves the creation and manipulation of view hierarchies. To achieve congruence with the structure of these applications, a GraphQL query itself is a hierarchical set of fields. The query is shaped just like the data it returns. It is a natural way for product engineers to describe data requirements.

Product-centric: GraphQL is unapologetically driven by the requirements of views and the front-end engineers that write them. We start with their way of thinking and requirements and build the language and runtime necessary to enable that.

Client-specified queries: In GraphQL, the specification for queries are encoded in the client rather than the server. These queries are specified at field-level granularity. In the vast majority of applications written without GraphQL, the server determines the data returned in its various scripted endpoints. A GraphQL query, on the other hand, returns exactly what a client asks for and no more.

Backwards Compatible: In a world of deployed native mobile applications with no forced upgrades, backwards compatibility is a challenge. Facebook, for example, releases apps on a two week fixed cycle and pledges to maintain those apps for at least two years. This means there are at a minimum 52 versions of our clients per platform querying our servers at any given time. Client-specified queries simplifies managing our backwards compatibility guarantees.

Structured, Arbitrary Code: Query languages with field-level granularity have typically queried storage engines directly, such as SQL. GraphQL instead imposes a structure onto a server, and exposes fields that are backed by arbitrary code. This allows for both server-side flexibility and a uniform, powerful API across the entire surface area of an application.

Application-Layer Protocol: GraphQL is an application-layer protocol and does not require a particular transport. It is a string that is parsed and interpreted by a server.

Strongly-typed: GraphQL is strongly-typed. Given a query, tooling can ensure that the query is both syntactically correct and valid within the GraphQL type system before execution, i.e. at development time, and the server can make certain guarantees about the shape and nature of the response. This makes it easier to build high-quality client tools.

Introspective: GraphQL is introspective. Clients and tools can query the type system using the GraphQL syntax itself. This is a powerful platform for building tools and client software, such as automatic parsing of incoming data into strongly-typed interfaces. It is especially useful in statically typed languages such as Swift, Objective-C and Java, as it obviates the need for repetitive and error-prone code to shuffle raw, untyped JSON into strongly-typed business objects.

Following video explains the syntax in GraphQL.

GraphQL opens up and talk about very powerful stream of concepts which allows us to rethink about our API designs. Even though it won't replace Restful APIs in all the contexts, there is a high chance of immediately dominating how the backends get exposed to the mobile clients.