Showing posts with label Programming Concepts. Show all posts
Showing posts with label Programming Concepts. Show all posts

Saturday, 19 May 2018

How to get the current time in milliseconds

Background

In many scenarios, we need the current time in milliseconds. In this post, we will see various methods to get the time in milliseconds since the UNIX epoch (January 1, 1970 00:00:00 UTC) in various programming languages.

How to get the current time in milliseconds

Following are ways you can get  current time in milliseconds for various programming languages -

  • ActionScript    
    • (new Date()).time
  • C++ 
    • std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()
  • C#.NET  
    • DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  • Clojure 
    • (System/currentTimeMillis)
  • Excel / Google Sheets*  
    • = (NOW() - CELL_WITH_TIMEZONE_OFFSET_IN_HOURS/24 - DATE(1970,1,1)) * 86400000
  • Go / Golang 
    • time.Now().UnixNano() / 1000000
  • Hive*   
    • unix_timestamp() * 1000
  • Java / Groovy / Kotlin  
    • System.currentTimeMillis()
  • Javascript  
    • new Date().getTime()
  • MySQL*  
    • UNIX_TIMESTAMP() * 1000
  • Objective-C 
    • (long long)([[NSDate date] timeIntervalSince1970] * 1000.0)
  • OCaml   
    • (1000.0 *. Unix.gettimeofday ())
  • Oracle PL/SQL* 
    •  SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000 FROM DUAL
  • Perl    
    • use Time::HiRes qw(gettimeofday); print gettimeofday;
  • PHP 
    • round(microtime(true) * 1000)
  • PostgreSQL  
    • extract(epoch FROM now()) * 1000Python  int(round(time.time() * 1000))
  • Qt  
    • QDateTime::currentMSecsSinceEpoch()
  • R*  
    • as.numeric(Sys.time()) * 1000
  • Ruby    
    • (Time.now.to_f * 1000).floor
  • Scala   
    • val timestamp: Long = System.currentTimeMillis
  • SQL Server  
    • DATEDIFF(ms, '1970-01-01 00:00:00', GETUTCDATE())
  • SQLite* 
    • STRFTIME('%s', 'now') * 1000
  • Swift*  
    • let currentTime = NSDate().timeIntervalSince1970 * 1000
  • VBScript / ASP  
    • offsetInMillis = 60000 * GetTimeZoneOffset()
  • WScript.Echo 
    • DateDiff("s", "01/01/1970 00:00:00", Now()) * 1000 - offsetInMillis + Timer * 1000 mod 1000



I recently investigated this as I wanted MicrosoftDateFormat in objective C. We can do this as follows -

  • NSString *date = [NSString stringWithFormat:@"/Date(%lld)/",(long long)([currentTag.firstSeenTime timeIntervalSince1970] * 1000.0)];


NOTE: timeIntervalSince1970 gives you the number of seconds whereas Newtonsoft.Json library (C#) gives it in milliseconds so you need multiple by 1000.0 to get milliseconds.


Related Links



Saturday, 20 January 2018

Difference between a forward proxy and a reverse proxy server

Background

Most of the companies out there have a proxy in between their corporate traffic and internet. This could be for multiple reasons - network security being one of them. In my previous post I showed how to set up a squid proxy -
That was basically a forward proxy. There are other type of proxies called reverse proxies. In this post we will see difference between them and how they work.

Proxy in lay man terms mean someone acting on behalf of someone else. This is the main principle behind forward and reverse proxy.

Forward Proxy :


Working :

Forward proxy sits between client machines and an origin server. Client machines make a request to the forward proxy with target as the origin server. Forward proxy then makes a request to the origin server, gets the response and sends it back to the clients. Clients in this case need to be explicitly configured to use this kind of forward proxy.

So to summarize a forward proxy retrieves data from another website (origin server) on behalf of the clients.

Example : 

 Consider three computers - A, B and C. Now A want to request a website hosted on computer C. In normal case it would directly be
  • A -> C
where computer A directly asks C for the website. However in case of Forward proxy there is an intermediate computer B. Computer A makes request to this computer B instead of directly making request to C. Computer B now makes a request to C gets the website and returns it back to the A. So the path would be
  • A -> B -> C.

When :

There can be multiple cases in which a forward proxy might be useful. Some are -
  • Client machines (Computer A in above case) are behind some firewall and have no access to internet and thereby no access to origin server.
  • A company wants to block some of the malicious sites. They do this on the forward proxy and make sure all client make request via this proxy.
  • A forward proxy also has feature to cache requests so that the response time is minimum.



Reverse Proxy :

Working : 

Forward proxy was used to shield the client machines where as a reverse proxy is used to shield a origin server. So client machines make call to the reverse proxy as if they are the origin servers. Reverse proxy now makes a call to the actual origin server and returns the response back to the client.

Example :
Let's consider a similar example of 3 computers - A,B and C. Again in a normal scenario A would directly request website from C.
  • A -> C
In case of reverse proxy there is a computer B which hides C behind it. A makes call to B instead and B fetches the website from C and returns it back to A. So the path is again -
  •  A -> B -> C
When: 
  • Provide internet users access to a server that is behind the firewall.
  • Load balance backend servers.
  • Typical CDN deployment. Proxy server would tell the client the nearest CDN server.


 Difference between a proxy and a reverse proxy server

 If you see the example above in case of both forward and reverse proxy path is always -
  • A -> B -> C
In case of forward proxy B shields machine A by fetching content by C itself and sending back to A. Where as in case of reverse proxy B shields C by fetching the data from C and sending it back to A.

In case of forward proxy, C would think that B is the machine sending it request where there could be multiple A's behind B. Similarly  in case of reverse proxy A would think that it is sending request to C but it would actually be a request to B and B would in turn talk to multiple C and send back the request to A.








NOTE: It's just nomenclature. As you take a basic reverse proxy setup and start bolting on more pieces like authentication, rate limiting, dynamic config updates, and service discovery, people are more likely to call that an API gateway (https://www.nginx.com/blog/building-microservices-using-an-api-gateway/).


Related Links

Saturday, 20 May 2017

Left shift and right shift operators in Java

Left shift and right shift operators in Java

A lot of time we use >> , >>> or << and <<< operators in Java for bit operations. These operations essentially shift bits left or right depending on the operator. In this post we will see what exactly is the difference.
  • >> is arithmetic or signed shift right
  • >>> is logical or unsigned shift right
  • << is arithmetic or signed shift left
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.

The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

NOTE : There is no logic left shift as it is same as arithmetic left shift.

Example :

        System.out.println(Integer.toBinaryString(-121));
        // prints "11111111111111111111111110000111"
        System.out.println(Integer.toBinaryString(-121 >> 1));
        // prints "11111111111111111111111111000011"
        System.out.println(Integer.toBinaryString(-121 >>> 1));
        // prints "1111111111111111111111111000011"
        
        System.out.println(Integer.toBinaryString(121));
        // prints "1111001"
        System.out.println(Integer.toBinaryString(121 >> 1));
        // prints "111100"
        System.out.println(Integer.toBinaryString(121 >>> 1));
        // prints "111100"


As you can see in case of -121 since it is a negative number arithmetic or signed shift right adds a 1 to the rightmost bit where as in case if 121 it adds 0.

logical or unsigned shift does not care about sign. It just adds 0 to the shifted bits.


Related Links

Sunday, 8 May 2016

Understanding Tries data structure

Standard Tries

The standard Trie for a set of strings S is an ordered tree such that
  • Each node but the node is labelled with a character
  • The children of a node are alphabetically ordered
  • The path from external nodes to the root yield the String of S.

For example see following picture -



How would you represent this in code? Each node will have an array of size 26 (assuming all english characters) where each index of array will store pointer to next node which is essentially next character of the string.

Running time for operations

  • A standard trie uses O(W) space.
  • Operations find, insert, delete take time O(dm) each where
    • w = total size of strings in S,
    • m = size of string involved in operation
    • d = alphabet size

Compressed Tries

  •  Trie with nodes of degree at least 2
  • Obtained from standart trie by compressing chains of redundant nodes.


 Applications

Trie has many useful applications like
  • Find first prefix in a text (pattern matching)
  • or auto complete a text (which is why it can be used in a search engine). The index of a search engine is stored into a compressed trie. Each leaf of trie is associated with a word and has a list of pages (URLs) containing that word called occurrence list. Trie is kept in memory while the occurrence lists are kept in external memory and are ranked by relevance.
  • Suffix tree (rooted directed tree whose edges are labelled with non empty substrings of S)


  • The suffix tree for a text X of size N from an alphabet of size d stores all the N suffixes of X is O(N) space. NOTE : There might be a case where a suffix is a prefix of another suffix in which case the suffix will end on an internal mode. To counter this case you can end the alphabet with a special character eg. $. Time complexity to build suffix tree - O(N^2)



Related Links



Saturday, 26 September 2015

SOAP vs REST Web Services

Background

        It's been around couple of months since this topic has confused me a lot. Every time I have discussion about webservices I always try to figure out difference between SOAP based web service (JAX-WS Java API) and REST based web service (JAX-RS) web service. When the picture is finally clear let me put it down for others.

Biggest point to note about SOAP and REST is that they cannot be compared!  Yes you read it right you cannot compare both. You can only do comparison of things that are different aspects of same thing and these are not. 

SOAP (Simple Object Access Protocol) is a protocol which uses XML to communicate data. Like any other protocol it has it's own rules. REST (Representational State transfer) on the other hand is an architecture (repeating architecture) meaning a way to design APIs. 

Given that we will see each in a bit more detail so that it gives us a clear picture of REST and SOAP based web service.

W3C defines a web service as
 "A software system designed to support interoperable machine-to-machine interaction over a network."

SOAP based web services

  • SOAP stands for Simple Object access protocol.
  • As the name suggests this is a protocol. 
  • SOAP uses service interfaces and named operations to expose the APIS.
  • SOAP requires more bandwidth that REST requests.
  • You can only transfer (send/receive) XML payload from SOAP based webservices.
  • Java API for this is JAX-WS
  • SOAP has Web Services Description Language (WSDL) which describes how webservice will work and lets you get a reference to it.
  • SOAP based messages have strict specifications to follow for implementation.
  • SOAP defines it's own security standards WS-security..


REST based web services

  • REST stands for Representational state transfer.
  • This is an architectural approach.
  • REST uses URLs and method types (HTTP verbs like GET, POST, PUT etc) to expose APIs.
  • REST requires less bandwidth that SOAP based requests.
  • In REST you can send and receive any type of payload (Json, XML, HTML).
  • Java API for this is JAX-RS
  • REST does not have strict restrictions like SOAP.
  • For security REST calls rely in underlying protocol like HTTPS.


Generic Notes

  1. HTTP verbs used by REST
    1. GET
    2. OPTION
    3. POST
    4. PUT
    5. PATCH
    6. DELETE
  2. Careful with HTTP POST verb. It is not safe and not idempotent.So You cannot just resend.
  3. In REST based requests , response may be cached. Server may return ETag header when accessed. Client send this tag on subsequent request to access resource. If resource is not changed server will return 304 (not modified).




Major differences between GET and POST

 

Related Links 


 

Sunday, 5 April 2015

Difference between functions and methods.

Background

Let me be honest here. I always thought they are the same and used them interchangeably but as it turns out they are not. Each has it's significance or scope.  I stumbled on this question today when I started with python again after a long time. I simply googled "methods in python" and the results on different pages  were using different terminology. And that's when it struck me that methods and functions are indeed different and we should be careful to use each in proper context. I will tell what to use it context of few programming languages but lets start with the understanding process.



I believe programming can be fun.  Above is my 1st meme so please bear with me :)

Difference between Functions and Methods

 Ever tried to explain anyone what a method or function is ? You may have read some definition back in college. Anyway lets try to explain that first.


So a function has a name (called as function name). There it has the data that is passed to it that the function can operate on (called arguments). There arguments are generally provided in parenthesis "()" adjacent to the function name. And lastly there is method body that has the logic to execute when this code module is called. If you ask about a method you may probably answer the same way. 

But there is a difference. 
  • Functions are standalone where as method are associated with an Object. When you call a method it is in scope of that object which has it's own blueprint (called class).  
  • Another difference is that all arguments in function are explicit where as method had one implicit argument and that is reference to the object that the method belongs to. For example methods in Java can use this  in the method body or in python you can use self.
Just think of "Methods" as object oriented way of calling "Functions.

Note :  I can understand if you argue back saying what about static methods in Java? They are not associated with any instance and we definitely cannot use this in static methods. So are they still methods? Well answer is Yes. You will still call them methods. As I said "Methods" are object oriented way of calling "Functions". I know this is a lame argument but that is what it is. Do let me know in comments if you have some other view point. Would love to discuss this :)


Example in Python

I will give example in python due to which this all started for me. We can have both functions and methods in python. Hope it helps to understand this better.

Functions in python :

def test(name, place="India") :
    """ This is a test function"""
    print("Hi " + name + "! Welcome to " + place)


test("Aniket", "USA")
test("John")

Methods in python : 

class TestClass:
    def test(self, name, place="India"):
        """ This is a test method """
        print("Hi " + name + "! Welcome to " + place)

testObj = TestClass()
testObj.test("Aniket", "USA")
testObj.test("John")
 

And you should see output as (in both cases) : 



General Terminology

  • For Java, there are only methods.
  • For C, there are only functions.
  • For C++ or Python it would depend on whether or not you're in a class.


Note : I know I have labelled this post as "programming concept" but it is more of a terminology use. There were many instance when I answered on Stack overflow using these words interchangeably and ended up corrected by someone and each time I am like "What.... how does it matter?". Well it does .. specially when you are in a circle of programmers/developers. So better late than never :)  you know now!

Related Links


Sunday, 22 February 2015

Java Class Design using Builder

Background

Two important principle of Object Oriented programming are - 
  1. For each class design aim for low coupling and high cohesion.
  2. Classes should be open for extension but closed for modification.

We will see how we can use these to design any classes.



Class Design


Lets design a simple Employee class which has it's name.

public class Employee {
    
    private String name;
    
    public Employee(String name)
    {
        this.name = name;
    }
    
}


Looks good. Every time anyone has to create an instance of Employee he has to supply name in the constructor. So you see any flaw in this?

Well there is. Lets say new requirement comes up and you now have to add employee age. What would you do?

One way would be change the constructor to include age now.

public class Employee {
    
    private String name;
    private int age;
    
    public Employee(String name, int age)
    {
        this.name = name;
        this.age = age;
    }  
}


Though it solves our new requirement it will break all our existing code. All Users using our existing code will  have to make changes now. So we definitely cannot remove the constructor with name in it. So what do we do next ?

Lets create an overridden constructor.

public class Employee {
    
    private String name;
    private int age;
    
    public Employee(String name)
    {
        this.name = name;
    }
    
    public Employee(String name, int age)
    {
        this(name);
        this.age = age;
    }
    
}


Ok this looks good. This will not break existing code and will meet our existing requirement. Now take a minute to this what about future requirements. Lets say you may have to add employees sex, salary etc in the Employee mode. What will you do then? Keep adding overloaded constructors?

Sure you can. But that is a very poor design choice. Simplest thing to do is following -

public class Employee {
    
    private String name;
    private int age;
    
    public Employee(){}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}


That's right. A simple no argument default constructor and getter, setter methods corresponding to instance variables. This is flexible design implementation. Going forward we can add as many instance variables with corresponding get and set methods.

Though this is good and simple class design. I would not say it is optimal. What if you want to ensure that user should not create a Employee instance without providing name.

Sure different developers will have different methods to ensure that and have good design. I like to use builder for that. See following -


import static org.apache.commons.lang3.Validate.*;
public class Employee
{
    private String name;
    private int age;
    
    private Employee() {}

    public String getName()
    {
        return name;
    }
    
    public int getAge()
    {
        return age;
    }

    public static class EmployeeBuilder
    {
        private final Employee employee;

        public EmployeeBuilder()
        {
            employee = new Employee();
        }

        public EmployeeBuilder setName(String name)
        {
            employee.name = name;
            return this;
        }
        
        public EmployeeBuilder setAge(int age)
        {
            employee.age = age;
            return this;
        }

        public Employee build()
        {
            validateFields();
            return employee;
        }

        private void validateFields()
        {
            notNull(employee.name, "Employee Name cannot be Empty");
            isTrue(employee.age >= 21, "Employee age cannot be less than 21");
        }
    }
}



Notice following points -
  1. We made constructor of Employee class private. So no one can directly instantiate Employee class. He or she has to use our Builder class.
  2. There is not setter methods in Employee class. Again builder should be used.
  3. Builder's build() methods validates our requirements like name cannot be null or age has to be more than 21.
  4. You can easily create Employee objects using - 
Employee employee = new EmployeeBuilder().setName("Aniket").setAge(23).build();

Saturday, 24 January 2015

Getting started with IBM Bluemix

Background

A while ago I had written a post explaining difference between SaaS, PaaS and IaaS.

In PaaS if you see examples IBM Bluemix is one of the PaaS solutions. In this post we will explore it in detail. Bluemix is powered by Cloud Foundry open source project which itself is a PaaS solution.

For more details on why you should use IBM bluemix, what are the benefits you can refer to following slideshare PPT -


Getting Started

You can sign in into Bluemix portal with following URL - 

You will need an IBM ID for the same. If you don't have you can create one. Once you login you should see following dashboard section -


 Once you have the Dashboard you are all set to create and deploy App of your own. Go ahead and Click on Create An App.

Creating an App

  • Click on Create An App



  • You will be prompted to choose what type of App are you creating ? Is it a web app or a mobile App? For this demo tutorial lets select web app.
  • Next on selecting WEB you will get options to select from various runtimes like Java, NodeJS etc...


  •  For this demo I am choosing NodeJS as it will be easier to demonstrate final outputs. Choose SDK for Node js and click continue.
  • You will then be asked to enter App Name. This will for unique root to your Application. So if some name is already taken you have to give another one (just like domain names :) )


  •  Put some name. I had put DemoWebApp but unfortunately it was taken. So I have put it as DemoTestWebApp. We will see it is next screenshots. Anyway click on finish and your template App should be created, built and deployed.



  • Let see how it looks like, shall we?

See the Route field in above screenshot? That is unique url that points to your App. Go ahead click on it or copy paste it in the URL of your favorite browser. You should see following -


  •  Yeah we create our template App...big deal? What the fun unless we modify it and give it our flavor :)

Modifying and deploying your own code

If you see start coding section under dashboard you should see various methods in which you can build your code.

  •  Yes it provides seamless integration with GIT. Fell free to try out any/all methods. For this demo I am going to use the CF (Cloud foundry) CLI(command line interface). This section gives you list of exact steps that you need to do for creating a local copy of code, changing it and deploying it. But will  re do them for better understanding -

    • Download and install CF CLI from here. I am using Windows. You can choose installer which suits your requirement.... Debian, Redhat, Mac OS X, Windows etc.
    • To verify that it is correctly installed you can simple type cf -v in your command line and it should print you the version. For me it gives -

      C:\Users\athakur>cf -v
      cf version 6.9.0-620f841-2015-01-20T18:01:40+00:00
    • Next Download the template code. Link to it should be in the same CF CLI section of  Start coding section. Go ahead and download the zip file (DemoTestWebApp.zip in my case) and extract it.
    • Lets make some changes to the code now. Example code makes use of Jade Node template engine. The pages that are rendered are in views folder of extracted folder.
    • I have changed some line of code in body.jade file.  For the changes that I made and how can we deploy these changes see following screenshots - 

body.jade File Content

//- body.jade
//- This file provides the HTML body part.


body
  table
    tr
      td(style= "width:30%;" )
        img(src="/images/newapp-icon.png")
      td
        h1 Welcome to Bluemix!
        p This is a demo web app created with <span class = "blue">NodeJS Starter Application</span> by <span class = "blue">Aniket Thakur</span>. Happy Coding!



Now lets deploy our code -

  • Navigate to App directoru ->  cd C:\Users\athakur\Sources\WebTestAppDemo
  • Next connect to bluemix -> cf api https://api.ng.bluemix.net 
  • Login -> cf login -u yourUserName
  • Setup target -> cf target -o yourOrganization -s yourSpace
  • Finally push your code -> cf push DemoTestWebApp 

Finally you should see something like -


1 of 1 instances running

App started


OK

App DemoTestWebApp was started using this command `node app.js`

Showing health and status for app DemoTestWebApp in org *********** / space at
hakur as *************...
OK

requested state: started
instances: 1/1
usage: 128M x 1 instances
urls: demotestwebapp.mybluemix.net
last uploaded: Sun Jan 25 06:28:12 +0000 2015

     state     since                    cpu    memory          disk
#0   running   2015-01-25 11:59:01 AM   0.0%   18.1M of 128M   35.9M of 1G



This means your code is deployed and your app is restarted. All you have to do now is revisit your App URL and test out the changes.


  Lastly I would say it always fun to try new technologies. So do give this a try. It will surely make your life easier (it terms of app deployment and maintenance ofcourse :) )


Related Links

Understanding SOA (Service Oriented Architecture)

Background



Lets say you are designing a system to process stock rates that you receive from stock exchange. Lets say you develop a web application that expects a JSON object. Maybe in further processing down the workflow some other format is expected. To integrate various such services and inter communicate in platform independent way SOA is used. SOA suites provides easy way to integrate such services.



SOA and ESB

SOA is service oriented architecture. In SOA services are decoupled and can interact with each other irrespective of the service type. Meaning a particular service can be platform or protocol specific but SOA enables such services to interact and exchange data. This data is essentially exchanged via ESB (Enterprise service bus) which forms the backbone of any SOA architecture.

Let me go ahead and give specific example to help understand this better. One way ESB could be implemented us by using JMS servers and using XML/XSD as means of transferring data between various services. So various service will register or connect to these JMS servers and exchange data using XML format. Generally SOA suite comes bundles with so called adapters that help transforming messages to and from format understood by service and XML.

For example consider shares trading system. Messages from stock exchange come in FIX protocol. You may have build an application that expects JSON. To make these both systems work you will use SOA - FIX Adapter will convert FIX message to XML, then this xml will be transferred to JSON Adapter over ESB which will then convert to JSON as required by your system endpoint.

Note : I have mentioned XML as it is platform independent message format. It is in fact SOAP (Simple Object access Protocol) that is used to transfer messages. SOAP is a standardized xml with already defined and recognized specifications.

Finally hoping following picture makes it very clear.




Related Links

Friday, 23 January 2015

Difference between SaaS, PaaS and IaaS explained

Background

When decision is made that the business you are trying to create depends on cloud services you need to choose between one of the following deployment models - 
  • IaaS (Infrastructure as a Service)
  • PaaS (Platform as a Service)
  • SaaS (Software as a Service)

Simply speaking following diagram should tell you what each model represents -


Lets discuss in details about each of the cloud models  -

 SaaS (Software as a Service)

SaaS is the simplest cloud service model that serves the end users. All end users have to do is log into the cloud service from a client (typically a browser) and start using the service - Excellent example here would be GMail . All you do is log into your gmail account and send/receive mails.

Target Audience : End Users

Benefits : It saves you the trouble of creating and maintaining software's by yourself. I gave Gmail as an example for SaaS above. Now think you are starting your own business/company and you need to communicate via emails.  If you start from scratch you will have to have your own mail server, configuration and most importantly it's maintenance . SaaS lets you delegate this to 3rd party (SaaS vendors) - Gmail in our example. 

Working : SaaS generally works on Subscription model. You pay for the duration of time you are using the services. Some SaaS based companies may give out free trials for some trial period or give some basic features for free to end users to try out. For example Gmail - if you exceed the space quota available you have to pay for the extra space.

Example : Look around you -  the services that you use in day to day life. Gmail, Salesforce, DropBox, Cisco WebEx, Google Forms, Google Docs, Microsoft 365 etc.





PaaS (Platform as a Service)


PaaS comes at a level lower than SaaS. PaaS allows you to deploy your code without bothering about underlying runtime ,operating system or server infrastructure. Best example here would be - Google App Engine . You choose what programming language suits your business model - Java, NodeJs, PHP ... , write code and deploy it on the PaaS provider. 

Target Audience : Developers

Benefits : It saves you the trouble of owning and maintaining servers (data centers), operating systems on it, runtimes needed to build and deploy your application etc. PaaS delegates these infrastructure requirements to 3rd party (PaaS vendors) - Google App Engine in our example.Also you don't have to worry about scaling and performance. 

Working : So lets say you have written a code for the service you want to provide but dont want to bear the additional cost of purchasing and maintaining infrastructure required to build and deploy your code. So you go to a PaaS vendor and deploy your code there. Again this is pay as you use model. You will have some memory space / RAM  allotted to you for free. As your application scales, your customer base increases you will have to pay for that. Best thing about this is that you don't have to pay unless your requirements exceed the ones provided by the PaaS vendor.

Example :Unless you are a developer I don't expect you to know these but here are some example - Google App EngineCloud Foundry, Heroku, IBM Bluemix, Red Hat’s OpenShift.



 IaaS (Infrastructure as a Service)

This is the lowest level of cloud services that are provided. This saves you the trouble of actually buying and maintaining server infrastructure. In this you get servers from IaaS vendor. You choose your own OS, your runtimes, your application code etc (Refer to topmost picture to visualize).  Famous example of this is AWS (Amazon web services).


Target Audience : Typically IT Admins

Benefits : It saves you the overhead of maintaining hardware infrastructure. You directly get the servers from IaaS vendor.

Working : This generally works using virtual environments. IaaS vendor will have data centers each having multiple servers. Each server will have multiple virtual machines running on them and each IaaS customer will get such a virtual machine. You can then decide what OS you prefer, what runtimes you need etc. Note  as a IaaS customer you will get the experience of a full server + OS stack. You will never know that it infact is virtual environments. How this actually works will of-course depend on the vendor. As far as AWS goes you can try it out for one year without any charges with specified data limits. After a year you will be charged.

Example :Examples for IaaS vendors are AWS, HPCloud, CloudSigma etc.


Summary

 To summarize each of these cloud models have their own uses, So choose according to your business model.


Thursday, 13 November 2014

Difference between Association, Aggregation and Composition in UML, Java and Object Oriented Programming

Background

In Object oriented programming a program is essentially multiple objects interacting with each other. Each interacting object have a relation. This relationship can be categorized as -
  • Association, 
  • Aggregation and 
  • Composition
Note these are not mutually exclusive (We will come to that in a while). But given a relationship between a Class or it's object their interactions can be described with above categories. Also to represent these relationships there are UML diagrams (Wiki) . For example we may have Class diagram or Use case diagram or a timeline diagram. Above classifications are also used in these UML diagrams.


Difference between Association, Aggregation and Composition


When we think of Object oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words object of one class may use services/methods provided by object of another class. This kind of relationship is termed as association.

For example you are related to your parent. In other words you are associated with your parent. This type of generic relationship is called association.




Aggregation and Composition are subsets of association meaning they are specific cases of association.


  • In both aggregation and composition object of one class "owns" object of another class.
  • But there is a subtle difference. In Composition the object of class that is owned by the object of it's owning class cannot live on it's own(Also called "death relationship"). It will always live as a part of it's owning object where as in Aggregation the dependent object is standalone and can exist even if the object of owning class is dead.
  • So in composition if owning object is garbage collected the owned object will also be which is not the case in aggregation.



Confused? Lets take examples to understand Composition and Aggregation

  • Composition Example :Consider example of a Heart and an Human. This type of relation ship between Human and Heart class is called Composition. Object of Heart class cannot exist without object of Human class and object of Heart has no significance without Human class. To put in simple words Humanclass solely "owns" the Heart class.



  • Aggregation Example :Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning Car object own Wheel object but we cannot say Wheel object has no significance without Car Object. It can very well be used in a Bike, Truck or different Cars Object.




Summing it up


To sum it up association is a very generic term used to represent when on class used the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.




Note : For Association you can either use an arrow depicted above or a simple line. In Argo UML (Wiki) tool which I use we can choose from either. For example above association diagram for Parent-Child can be


Related Links

Sunday, 5 October 2014

What is object-oriented programming? - By Steve Jobs

Background

If you know Java or C++ then you are already familiar with what Object oriented programming. It is a simple yet tricky concept to understand. I was browsing through some of the programming questions on Quora and came across this answer about OOP. It is as described by Steve Jobs in an interview. I am not aware of the source for this but I am still going to go ahead and put it down here as it is a very good real life scenario to illustrate what OOP is.


What is object-oriented programming? - By Steve Jobs


Here, in an excerpt from a 1994 Rolling Stone interview, Jobs explains what object-oriented programming is.


Jeff Goodell :  Would you explain, in simple terms, exactly what object-oriented software is?

Steve Jobs : Objects are like people. They’re living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things. And rather than interacting with them at a very low level, you interact with them at a very high level of abstraction, like we’re doing right here.
Here’s an example: If I’m your laundry object, you can give me your dirty clothes and send me a message that says, “Can you get my clothes laundered, please.” I happen to know where the best laundry place in San Francisco is. And I speak English, and I have dollars in my pockets. So I go out and hail a taxicab and tell the driver to take me to this place in San Francisco. I go get your clothes laundered, I jump back in the cab, I get back here. I give you your clean clothes and say, “Here are your clean clothes.”
You have no idea how I did that. You have no knowledge of the laundry place. Maybe you speak French, and you can’t even hail a taxi. You can’t pay for one, you don’t have dollars in your pocket. Yet I knew how to do all of that. And you didn’t have to know any of it. All that complexity was hidden inside of me, and we were able to interact at a very high level of abstraction. That’s what objects are. They encapsulate complexity, and the interfaces to that complexity are high level.



Let me relate the above in a more technical way. There are various things that define each individual - their name, gender, age, country they live in, language etc. This is the structure of "people" and the different values for each parameter define unique individuals. This is nothing but Classes which define how your Objects are in Java. The person asking for laundry and the person carrying out the task are both different Objects. What Jobs meant by saying that the person requesting for laundry is not aware of the complexities involved in carrying out the actual process is actually what is termed as data encapsulation. All that is done here is delegate task to type of Objects that understand the task. If you go a few steps ahead all - the Cab, the Laundry, the laundry man are all Objects. Laundry man Object knows where to get the laundry done but how do we get there ? He will need a Cab Object where he would say take me to  X place. Now the Cab object knows how to drive from place A to place B. So Laundry man does not have to worry about the complexities of getting to laundry place. If you see a broader picture we all in day to day life are all Objects with specific attributes and function and we continuously interact and delegate to work as a System. This System is nothing but the Java program and the ecosystem is nothing but the JVM (Java virtual machine).


Some characteristics that define a OOP design - 

1. Object              -    Instance of Class
2. Class                -    Blue print of Object
3. Encapsulation   -    Protecting our Data
4. Polymorphism  -    Different behaviors at different instances
5. Abstraction      -    Hiding our irrelevant Data
6. Inheritance       -    Object inheriting propertied from it's parent.



Related Links

t> UA-39527780-1 back to top