Friday, 30 September 2016

Immutable objects

An immutable object is an object whose state cannot be modified after its creation. Once object is created, you can not change the properties of it. Immutable object is sort of design pattern. We have to follow certain rules or patterns to create immutable objects.

In java, once you initialized an object , you'll never be allowed to set the values of its property through the setter methods and not to be allowed to have any method that will change the state of the object. You will only be allowed to set the values at the time of object creation through constructor arguments. Mutable property of the class will never be assigned even through the constructor. Instead, it will copy the values from the arguments and getter method will also make another copy to return to the caller.

One last thing is that it's a final class, You will never be allowed to inherit it, which means you can not create sub class of it.
We can get a better understanding, when we look at the below code.

Example:

public final class Product {
 
 private final String productId;
 
 private final String productName;

 private final String companyName;
    
 private final List versions;
 
 public List getVersions() {
  return new ArrayList(versions);
 }

 public String getProductId() {
  return productId;
 }

 public String getProductName() {
  return productName;
 }

 public String getCompanyName() {
  return companyName;
 }
 
 public Product(String productId,String productName,String companyName,List versions) {
  this.productId = productId;
  this.productName = productName;
  this.companyName = companyName;
  this.versions = new ArrayList(versions);
 }

}


String and Integer objects are the examples of immutable objects in JDK.


Summarising the guidelines below,
Final class - can not create subclass
No public setter method - Can not set or change properties
No public method that will change the object state
Constructor argument- set properties, while creating objects.
Copy mutable property - while setting through constructor and returning through the getter.


When/where to use:

We are fetching some meta data from the data base and those data should not be updated by the user. So here, we can store those data in an immutable object and use it to avoid altering the original data.
Let's consider Amazon or Flipkart application. You can not modify the price, item name, description, review comments,etc in the item which you want to buy. So you can have immutable objects in your code to hold all these metadata to avoid modifying and updating the values in database.

In a multithreaded environment, we can safely use the immutable objects. If we use mutable objects without any need in such places, possibly there could be the chances of creating concurrency issues. For example, one thread is trying to change the state of an object, while another thread is accessing the state of it.
To avoid this, we have to make methods synchronized. Synchronizing methods may cause performance issues. So if we use immutable objects in multithreaded environment, we can come out of these issues and focus only on the other part of implementations.

Caching immutable objects is safer than the mutable objects. If a map has objects for its keys, we have to consider using immutable objects to avoid changing states. Because in most cases, hashcode value is calculated based on the object state.

For Javascripts, visit http://flexydevcenter.blogspot.com/


Friday, 16 September 2016

JQuery ajax GET request call

Below is the example of an jQuery ajax call. It's making a GET request.

 <head>  
      <script>  
      $( document ).ready(function() {  
           $( "#mainMenuArea" ).load( "html/mainMenu.html" );  
           $.ajax({url: "http://localhost:8080/services/usersproducts/allproduct",   
             success: function(result){  
                var productArray = result.products  
                $( "#div_appArea" ).append("<table>");  
                $( "#div_appArea" ).append("<tr><th>Mobile No<th><th>Possession Status<th>");  
                $( "#div_appArea" ).append("<th>Company Name<th><th>Recommended<th></tr>");  
                $( "#div_appArea" ).append("<th>User Product Id<th><th>Recommended<th></tr>");  
                for(var i in productArray){  
                     $( "#div_appArea" ).append("<tr>");  
                     $( "#div_appArea" ).append("<td>"+productArray[i].productId+"<td>");  
                     $( "#div_appArea" ).append("<td>"+productArray[i].productName+"<td>");  
                     $( "#div_appArea" ).append("<td>"+productArray[i].companyName+"<td>");  
                     $( "#div_appArea" ).append("</tr>");  
                }  
                $( "#div_appArea" ).append("</table>");  
        }});  
      });  
     </script>  
 </head>  
 <body>  
     <div id="div_appArea">  
 </body>  

Saturday, 27 August 2016

Quick sort

Introduction
Pivot , Divide and Conquer , Wall , Randomized algorithm are the four terminologies we should know, when come to quick sort.

Pivot value selection:
Randomly select an element from the array. Here, we are choosing the last element as a pivot.

Wall:
Left side of the wall will always have the values that's smaller than pivot. Right side will always have bigger values.The index of the wall will start at the start index and keep moving on. 

Comparison:
Compare the elements from wall to pivot, with the pivot value. If we found any value less than the pivot, swap the value with wall and move the wall by one index. Once you did the comparison of all elements with pivot, swap the pivot with wall. Now the pivot has placed successfully in its position.

Divide and conquer:
Now if we divide the elements by the wall, we get 2 arrays. Continue the same process again as we mentioned above. No need of conquering.

Look at the below code to get the better understanding,

Code:


public void doQuickSort(int[] a,int strtIdx,int lstIdx) {
 int pivotValue = a[lstIdx];
 int wall = strtIdx;
 for(int i=strtIdx;i < lstIdx;i++) {
  if(a[i] < pivotValue){
   swap(a,wall,i);
   wall++;
  }
 }
 swap(a,wall,lstIdx);
 if(strtIdx < wall-1){
  doQuickSort(a, strtIdx, wall-1);   
 }
 if(wall+1 < lstIdx){
  doQuickSort(a, wall+1, lstIdx);   
 }
 System.out.println();
 for(int i=0;i < a.length;i++) {
  System.out.print(a[i]+" ");
 }
}
Complexity:
The time complexity of this sorting is O(n2) in a worst case scenario. The worst case is when your pivot value is always the smallest or largest element than rest of the elements. Each time if the list is divided into 2 equal sized list, then the complexity will be O(nlogn) which is the best case complexity of this algorithm. 

Tuesday, 12 July 2016

Bubble Sort

Prerequisite:
Algorithm, Sorting, Asymptotic complexity(time complexity, space complexity)

Introduction:
Bubble sort may look same as insertion sort, because the outcome of the bubble sort looks same as insertion sort. In case of sorting in ascending order, Insertion sort will keep taking out the min value at end of the each iteration, whereas bubble sort will take out the max value. So both insertion and bubble sort look same.But there are few differences, when you look at the implementation.

Code:

 public int[] doBubbleSort(int[] ip) {  
      boolean isSwapped = false;  
      for(int i=1;i<ip.length;i++){  
           for(int j=0;j<ip.length-i;j++){  
                if(ip[j]>ip[j+1]){  
                     swap(ip, j, j+1);  
                     isSwapped = true;  
                }  
           }  
           if(!isSwapped){  
                break;  
           }  
      }  
      return ip;  
 }  

Complexity:
The time complexity of this sorting is O(n2) in a worst case scenario. In a best case scenario where the list is already sorted, the time complexity is O(n). The auxiliary memory/space is taken by this algorithm will never increase based on the number of elements. It always use the constant extra space. So the space complexity is O(1).

When/where to use:
Even though it has the interesting implementation and the fancy name, it will not be suitable for any case. We can say It's suitable for smaller array which has 10 or 15 elements, because of easy implementation. You can also use this algorithm, if the array is already sorted where the complexity is O(n). But in such cases, insertion sort is a better choice than this.

Sunday, 10 July 2016

JMS

(The main objective of this article is to identify the places where JMS is needed)

JMS(Java messaging service) is a widely used technology. It has two different mechanism called Queue and Topic(publish-subscribe). A queue may have multiple listeners. But when u push a message, it will be picked up by only one listener whereas in topic, message will be received by all the subscribers who subscribed to the topic.

So now the question is where does it need?

Let's consider a case, you have a centralised database which has to be updated by the multiple applications. But you don't want other application to access this database. So here, you can have a queue and all the applications will just push their data to this queue. You will take care of dequeue them, process them & store them in the DB.

In another case, you need to send a mail and call a web service, before Storing the user data into your application database, when user submit a request.

Here, there's no guarantee that the email service and the web service will always be up and running. So the entire flow will fail or we have to skip the mailing part and/or calling web service, if they are down. Even though both the servers are up, there'll be some delay in storing data and sending the response back to the user with respect to the time taken by the external services.

To avoid such issues, we can have a queue where we push the messages and go ahead with the storing data in DB. A separate JMS listener component will take care of sending emails and calling/updating the web service.

You may think that we can store the same data which we are pushing to the queue, in DB and later, we can fetch them from DB and process them.Yes, you can also use DB. If you are ok to expose your database to other components or if you want to store those data permanently or if the size of the message is large, you can go for DB instead of queues.

If your application needs to send a message to multiple applications/components, you may go for the topic. As we told before, if a message comes into the topic , it will be received by more than one subscribers which is actually an another application or component. Queue and Topic both can be used as a middleware which use to connect components/applications written in various languages.

Thursday, 7 July 2016

Insertion sort

Prerequisite: 
Algorithm, Sorting, Asymptotic complexity(time complexity, space complexity)

Introduction:
Insertion sort will take elements from 0 to n and compare & swap it with the left part of the array which is already sorted among the elements, until it find the right place where the element has to be. You may be clear, when look at the below code,

Code:
public int[] doInsertionSort(int[] ip) {
 for(int i =1;i<ip.length;i++) {
  for(int j=i;j>0;j--) {
   if(ip[j]<ip[j-1]){
    swap(ip, j, j-1);
   }else {
    break;
   }
  }
 }
 return ip;
}

Performance:
Time complexity of this sorting is O(n2) in a worst case scenario, O(n) in a best case scenario. O(n), when the array is already sorted. Worst case space complexity is O(1).

Where/when to use:
Even though it took more time or steps to sort the list than the other algorithms like Heap & merge sort, we still can use it in some places.It's easy to implement as selection sort, so we can use this for smaller arrays. But it may do more swaps than selection sort.
It's good to use this sort in a place where the element are all already sorted.Let's consider you already have a sorted list & a new element is added to the list. So now u need to place the last element in right place to make the list sorted again.

Tuesday, 5 July 2016

Design Patterns

          A programmer may write a better program to solve a problem. He may consider the memory management, Asympotatic complexity. 
          An Object oriented programmer will see everything as an object. Once he got the requirements, he can easily see all the objects or entities involved in it & he can write the services of the objects. 
          An application designer will figure out the relationship between the Objects and wire them by any design. A well designed application will help us in easy maintenance.
We can say that a better programmer would have all roles which We mentioned above.

There are several design issues have already been resolved by programmers. Below are the names of those design patterns,

  1. Observer pattern
  2. Decorator pattern
  3. Factory pattern
  4. Singleton pattern
  5. Command Pattern
  6. Adapter & Facade pattern
  7. Template method pattern
  8. Iterator & Composite pattern
  9. State pattern
  10. Proxy pattern
  11. Immutable Objects Pattern
  12. Mediator Pattern