Sunday, August 23, 2020

Understanding JavaScript Prototypal Inheritance for Java developers

Inheritance is a fundamental concept in programming languages. However, it is implemented differently in Object-Oriented Languages such as Java and Javascript. 

I have seen developers who move from OOP languages such as Java struggling to understand the JS Inheritance consequently end up not using it altogether which can also lead to inefficient code.  

In this post, I will try to explain the JS Inheritance also called Prototypal Inheritence especially for those who come from OOP languages.

Background

Let's quickly define Inheritance first. In simplest terms, it is a mechanism by which one object can acquire properties and behaviors or other objects. This is one of the main tenets of most common Object-Oriented Programming (OOP) languages and promotes reuse. This represents an IS-A or parent-child relationship. OOP languages implement what is called Class Inheritance.

Javascript also allows Inheritance but it is implemented entirely differently from OOP languages and is called Prototypical Inheritance. For OOPs languages such as Java has the concept of Classes and Instances and they are separate. Instances (objects or entities) are created from Classes (generalization or blueprints/definition) but in Javascript, there is no concept of class - you don't define a class and then create instances from them. 

Note that similar to Java language Javascript does not support multiple inheritances - the object has only one prototype and therefore can only inherit one object. Note that Java does support inheritance of more than than one interface.

Prototypal Inheritance

Before we talk about Inheritance in Javascript we need to understand what is a Prototype. 

All objects in JS can have properties that you define. For example, here object obj1 has two properties, foo, and bar

function Function1() {
this.foo = 'value1',
this.bar = 'value2'
}

In addition, all functions have one additional hidden property called prototype which by default is an empty object. Using this hidden property you can extend ALL objects created using function constructor (using the new keyword) and define new methods or properties. 

var obj1 = new Function1();
Function1.prototype.baz = 'value3';

Function1.prototype.getProps = function() {
return this.foo + ', ' + this.bar + ', ' + this.baz;
}

console.log(obj1.baz)
console.log(obj1.getProps())

Output

value3
value1, value2, value3

In the above example, we used the hidden prototype property of the object and enhanced or extended it by adding one property and a new method. Internally the prototype is implemented as __proto__ property and even though you can access it directly it should not be used directly. 

console.log(obj1.__proto__)

Function1 { baz: 'value3', getProps: [Function] }

The prototype object can also further have a __proto__ object. This is called the prototype chain. You can have another object that points to the same prototype as defined for the first object. During execution, the javascript engine starts at the top of the chain and works its way down till it finds the property in the prototype chain. The bottom of the prototype chain is Object{}. This mechanism of looking though the prototype chain is also called Delegate Prototype.

The example above uses Method Constructors and is considered an old way. 

Note that EC6 introduced the class keyword to Javascript language which you can use to create an object. Note that even though it looks like Classes in OOP languages such as Java, it is not the same. class in Javascript is a type of function and uses class instead of function keyword and also has a constructor method to initialize class properties based on the passed parameters. The only difference between Function constructor and using class forces you to use new keyword otherwise you will get an error.  

The new and preferred way (supported by newer browsers) is to use Object.create passing a prototype object and using dynamic linking to setup properties on the object. This is also referred to as Pure Prototypal Inheritance. You don't need to use class, extends, constructor, or super. 

var User = {
firstname: '',
lastname: '',
getName: function() {return this.firstname + ' ' + this.lastname},
}

var Member = Object.create(User);
Member.registrationDate = new Date();

var John = Object.create(Member);
John.firstname = 'John';
John.lastname = 'Doe'
John.registrationDate = new Date(2020, 7, 23, 10, 33, 30, 0);
console.log(John)
console.log(John.__proto__)
console.log(John.__proto__.__proto__)

console.log(John.getName())

console.log(John.__proto__.__proto__.__proto__)



Output
{
firstname: 'John',
lastname: 'Doe',
registrationDate: 2020-08-23T17:33:30.000Z
}
{ registrationDate: 2020-08-24T02:15:02.161Z }
{ firstname: '', lastname: '', getName: [Function: getName] }
John Doe
{}

Let's walk through the code and try to understand what's going on here.

First, We created a User object (initialized to default empty values for first and last names) using object literal syntax. Then extended the User object using Object.create and added a new property registrationDate set to the current date by default. Then created one user object John and passed Member object and overridden the default values. 

The first console log for John shows all the properties of John. 

The next two console logs show prototype chains. The first one pointing to Member object and the prototype of that points to User.

To resolve John.getName() JS execution context traverses the chain all the way to base object (User) and find the getName method and displays the first and last name. 

Finally, the console log statement logs the prototype of the base object which is an empty object {}.

The key thing to understand here is that even though you did not explicitly set the getName method on John object using prototypal inheritance it was able to access it. Note that if you now add a new method to any of the prototypal chain all the objects will inherit this new method. 


Finally, you can use prototypal inheritance to extend or override the behavior of built-in function constructors. For example, refer to this article.

Besides code reuse are there any other benefits of Prototypal Inheritance

Yes. The properties and methods in function constructor occupy memory. If you are instantiating a very large number of objects the attributes will be duplicated across all objects. While you do need attributes defined in the base object store the state variables there is no need to have functions methods that operate on object attributes to be duplicated across all objects. 

Using prototypal inheritance you can extend the behavior of all objects by defining them using prototypal inheritance thereby reducing the memory pressures. 

Sunday, August 16, 2020

Using GCP Source Repository, Cloud Build to configure automatic deployment of docker container on Google Cloud Run

Introduction 

In this article I will walk through the steps required to setup continuous integration environment and create build pipeline and automate deployment of a sample Angular App on Google Cloud Run. I will be using GCP stack end-end. Cloud Source Repositories for Git repository for version control, Cloud Build for creating docker containers which will be stored on Container Registry and then deploying the image on Cloud Run - serverless runtime environment. Finally, I will outline steps for configuring automated integration/deployment that will trigger builds and deployment of new version of application for any merge. 

Key Concepts and Services

Cloud Source Repositories - Fully managed free git repository from Google Cloud to storing and version control of source code. Tightly integrated with Cloud Build for triggering build for continuous integration. 

Docker - software that is most popularly used to build containers. Docker would combining the application code and set of instructions called DockerFile and produce a container that contains code all the required dependencies (listed as part of instructions in the docker file) to run the code. 

Containers - a self contained environment that can be run on many platforms 

Cloud Build - provide service similar to Docker and integrated with Cloud Source Repositories and can be triggered to produce container images and provides Continuous development and Continuous deployment. Cloud build can be configured to push the images to container registry and deployed to Cloud Run

Container Registry - Google Cloud Repository that can be used for hosting container images produced by Cloud Build

Cloud Run is fully managed serverless compute platform to deploy and running containerized application. Managed Serverless environment allows you to focus on your application and not worry about the underlying infrastructure or setting up and managing runtime environments. 

Saturday, August 08, 2020

Installing VNC Server on Google Cloud CentOS VM

Introduction

Recently I installed VNC on CentOS 6 on GCP for some development work. Sharing my notes. The steps are similar for Redhat Enterprise Linux.

Concepts

VNC - Virtual Private Networking, a Graphical User Interface platform that can be accessed remotely 

Steps

Create a VM

Create a CentOS instance in Micro VM Shape. To reduce latency choose a region close to you. Note that I'm using default VPC network that is automatically created. If you need more details on how to create VM pls refer my earlier blog

gcloud beta compute --project=oci-gcp-vpn-connectivity instances create centos-vnc-demo --zone=us-central1-a --machine-type=f1-micro --subnet=default --network-tier=PREMIUM --maintenance-policy=MIGRATE --service-account=71492557944-compute@developer.gserviceaccount.com --scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/trace.append --image=centos-6-v20200714 --image-project=centos-cloud --boot-disk-size=20GB --boot-disk-type=pd-standard --boot-disk-device-name=centos-vnc-demo --reservation-affinity=any

Tuesday, August 04, 2020

Hybrid Cloud - Setting up Site-to-Site IPSec VPN Connectivity between Oracle and Google Cloud

Introduction


As enterprises move to cloud there is a need to connect cloud-native applications with on-premise legacy systems. Multi-Cloud architectures allow you to build solutions spanning more than one public cloud by combining best of breed capabilities creating an increasing need for interconnecting these clouds. For example, you may want to use the Google App Engine to deploy your app but for your backend prefer Oracle ATP database hosted on Oracle Cloud. 

Each public cloud provides multiple connectivity options from dedicated high speed interconnect to using VPN based technologies to connect to on-premise using IPSec based connections that use public internet but provide secure connectivity.

Oracle OCI offers service called VPN Connect for site-to-site connectivity between an on-premise network with OCI VCN using VPN based on the IPSec protocol. 


In this blog, I will outline steps for configuring VPN between Oracle OCI Private Subnet with Google GCP VPC. VPN using IPSec is a cost-effective way of connecting these networks over public internet obviating no need for expensive lease lines and such. Steps outlined here also apply if you are trying to connect your on-premise network with either of these two cloud service providers. 

Note that I will focus on Site-to-Site connectivity based on IPSec protocol and use out-of-the-box functionality for VPN provided by these two cloud providers. You can also use other VPN implementations such as open-source Strongswan and Libreswan

Thursday, July 30, 2020

Creating a Utility VM on Google Cloud (GCP)

Introduction


This blog is in continuation of my previous article - Oracle OCI Cloud - Connecting a Private VM from a Public Bastion Host and walk through steps for creating a VM instance on Google Cloud GCP which we will use to establish VPN connectivity with Oracle Cloud - the steps for which will be outlined in next article in this series. 


Here's a quick reference of configurations for this VM that we will be using in the next article while configuring VPN connectivity


VPC: gcp-oci-vpn-demo

VCN CIDR: 192.168.0.0/16


Subnet: subnet1

Region:  europe-west1

Subnet CIDR: 192.168.0.0/16


VM: instance-1

Public IP: 35.210.10.232

Private IP: 192.168.0.2

Thursday, June 04, 2020

Oracle OCI Cloud - Connecting a Private VM from a Public Bastion Host

Introduction


The following outlines the configuration for connecting a backend private instance though a public instance in the same VCN but different subnets. 

This post talks about the necessary configurations of Router, Firewall, and builds a complete end-end example. 

High-Level Steps

  • Create VCN and two subnets (one public, one private)
  • Create VMs - one in each subnet
  • Configure Router
  • Configure Firewall
  • Test and Verify
  • Access to OCI Instance

Note this is part one of the multi-part series wherein we extend this example and do necessary configuration on OCI and try to establish Hybrid Connectivity to a private instance on Google Cloud (GCP) using VPN.

Pre-requisites

  • User with necessary privileges to create VCN, VM and configure networking
  • SSH key (public and private key pair) - Basic knowledge of networking - CIDR, Routers, Firewall, etc..

Understanding JavaScript Prototypal Inheritance for Java developers

Inheritance is a fundamental concept in programming languages. However, it is implemented differently in Object-Oriented Languages such as J...