Saturday, November 18, 2017

Java 9 - Try with Resource enhancements

Try With Resource
Introduced with Java 7, a try-with-resource provided a cleaner way to perform cleanup operations on resources. This was a very useful feature where you need not explicitly do a cleanup of resources (which implements an AutoClosable interface) but it was done automatically for us. This is critical in applications where we are dealing with resources such as Database, I/O Streams where not cleaning up the resources will be costly.

One limitation of pre-Java 9 try-with-resource was that it can perform cleanup operations only if the Resource was instantiated inside the try block.

For example (pseudo code):


// This will cleanup Resource
try(Resource myResource = new Resource()) {
     resource.doSomething();
}

// The below will not work in pre-Java 9 but works in Java 9
Resource resource = new Resource();

try(resource) {
     resource.doSomething();
}

Will the above feature  be useful or complicate things depends on how this is used. Since the resource can be created elsewhere and passed on to this method or given via Dependency Injection, closing this can create more problems (as it lives outside the try block). So, this feature has to be used with Care.

Have a look at another interesting feature of Java 9 - Private methods in interfaces.








Java 9 - Private methods in Interface

Prior to Java 8, Java Interfaces can contain method signatures but without any implementation.

In Java 8, default methods were introduced where we can add new methods and a default implementation for the same. Though it was originally intended to allow people to add new interface methods without requiring all implementations to change (by providing a default implementation), we are using default methods in many different ways which may or may not be how it was originally intended to be used. If you have multiple default method implementations in an interface, we may end up having duplicate code due to lack of private methods.

Some options available to do this 
  • Another default method with common logic.
  • An external class containing Utility methods.
Both cases expose the implementation details to outside classes which otherwise supposed to be a private to default methods.

In Java 9, we can now create private methods in an interface which are to be used by default methods. 

So, if we have default methods in an interface and need to share a particular logic, a private interface method would allow us to do so without exposing that private method and all its implementation details via the interface (or a Utility class).

Have a look at an interesting enhancement in Java 9 - Try-with-resource enahancement

Thursday, November 9, 2017

Journey from CORBA to GraphQL

During my initial days as Software Engineer, my first exposure to client-server application was with a Java based server and a DotNet based client which used CORBA for remote communication.

RMI which is kind of predecessor of CORBA provided Java Only interfaces where as our application needed DotNet  (and Java too) which CORBA provided (had implantation in multiple languages).

Problem statement : We wanted a client server application where client can be either in Java or DotNet and server being Java.

CORBA which could solve the above problem was used and it served well during its initial days.

CORBA had some benefits (multi language support) but it lacked in few areas such as performance, clear specification and lack of complete symmetry in some field mapping. This RMI vs CORBA article provides good information and comparison on this topic.

When looking for options to replace CORBA, two options looked really attractive - REST service with JSON or API’s provided using ProtoBuf (from Google). Both were relatively new during that period and was gaining traction for their own reasons. Though we could not do much using Protocol Buffers, it is still quite popular with implementations where performance is of higher prominence. This blog has nice information on ProtoBuf. 

One more area I had a brief exposure to was SOAP based services. Schema, WSDL, tools to generate clients, contract between server and client applications - it has all good things that are needed for a client-server application. But dealing with XML based data and strong contract between client and server were some factors which made SOAP less attractive. SOAP and REST is discussed in this blog.

RESTful it was then, a very simple, HTTP based, JSON for data transfer over network and a stateless system. Looked very interesting to build our system which both java and DotNet clients can use. Converting all our entities into resources and having relationships as links providing a smooth navigation looked easily achievable. From then, I started working with different systems (due change in companies and products I worked on) where REST based services were used in different forms - some tried to be purest form, some with diverting from REST principles to have some functionalities stuffed in. Nevertheless usage of REST grew very fast and with evolution of SOA and micro services, fueled its growth further. I have used and still using REST in the services being developed where it is serving its purpose quite well.

Then came OData.

REST was good, but we wanted something more. A query type API's which gives client flexibility to add various querying capability into their service calls. Though OData does not completely adhere to original REST principles, it tried to balance contract between client-server (by providing $metadata) and fluent API's as in REST (Entity Models). OData was originally developed by Microsoft (2007) and many big players started contributing to specifications and standards. When I started working with SDL, a Java implementation of OData framework was developed for the use of our services implementation which was later open sourced. 

All was well with REST & OData except that we started having a new problem.

Problem statement: REST or OData based services makes complex client application to become chatty and also results in underfetching or over fetching of data. We want some genric way of providing API which can reduce number of calls to service and clients can ask for what they want.

Then came GraphQL.

GraphQL was developed by Facebook for internal usage and later made publicly available (2015). On very first instance, it addressed two important problems we were facing - reduce chattiness and prevent under-fetching or over-fetching of data (get only what you need). GraphQL (often confused with Graph Databases but has nothing to do with it) is a query language for API's and also provides resolving layer or ways to provide data for the query. 

REST or OData provided few of the features of GraphQL already, but GraphQL provides more elegant way of doing this. GraphQL mostly moves towards developing API's giving importance to what client need without the need for having a contract. During our initial evaluation of GraphQL, we identified potential benefits it can provide our clients. Moreover the rapid growth on the community around GraphQL makes is really interesting.

GraphQL fits well in todays application development requirement of ability to provide API's regardless of the client being used - Browser, Mobile, Tablet, etc. As an API provider, we need not worry about the type of client calling our API, but just expose types (schema) which our API will provide. Its the client implementation which queries the server to provide the data which is required and the GraphQL service provides only the data being requested. There are many articles around getting started with GraphQL and for Java, we have How to GraphQL which is great place to start with.

Overall it was an interesting journey from CORBA to GraphQL, the later being the one which looks like has a long way to go.





Wednesday, July 16, 2014

LinkedList<> over ArrayList<>?

LinkedList and ArrayList are two different implementations of the List interface of Java Collections Framework. LinkedList is implemented based on doubly-linked list where as ArrayList implements it with a dynamically resizing array.

These implementations differ in algorithmic runtime as shown below

For ArrayList
  • Accessing Data : get(int index) - Constant time O(1) - Reading is faster which is main advantage of using ArrayList
  • Adding new elements : 
    • End of list - add(E element) - If it fits into existing size of the list O(1). If the array is full and needs resize O(n) which is worst case
    • Add at a particular index (in between) - add(int index, E element) - This requires re indexing of all the elements after insertion position and hence in general O(n-index) and worst case will be O(n)
    • ListIterator.add(Element e) - Since we will adding at a position, it is same as adding an element at a index
  • Remove an element:
    • remove(int index) - As with adding elements at a particular index, removing (if not last element) requires re indexing all the elements after the element which is removed. So, in general it is O(n-index) and worst case is O(n).
    • remove(Element e) - It is same as removing at an index.
    • Iterator.remove() - Same as removing at an index.
For LinkedList
  • Accessing Data : get(int index) - O(n) - Reading is slower compared to ArrayList since we need to sequentially move towards the specified index to get the data.
  • Adding new elements : 
    • add(E element) - constant time O(1) only if you happen to have a pointer to the location where you are inserting (index). Else O(n-index)
    • add(int index, E element) - O(n-index) and worst case is O(n)
    • ListIterator.add(E element) is O(1)  - mainly because you are already at the index of the element after which element will be added. This is the main advantage of Linked Liked over ArrayList.
  • Remove an element:
    • remove(int index) - O(n) as we need to traverse to index and remove it. But we need not re index since only the pointers will be adjusted.
    • Iterator.remove() - O(1) same as ListIterator.add(E element). Again this is one of the main advantage over ArrayList.

As a conclusion,

LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list.

ArrayList, on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if you add more elements than the capacity of the underlying array, a new array (1.5 times the size) is allocated, and the old array is copied to the new one, so adding to an ArrayList is O(n) in the worst case but constant on average.

And one more important point to note here that memory requirements for LinkedList is more than ArrayList since it has to store the information about next and previous pointers. So, when we are looking at memory angle, we need to take this into consideration.

Choice of Data structure depends on specific use case and how we need to handle the add/remove and read operations on the data structure. During design, need to list all the possible uses of the data structure and finalize on optimized data structure to be used.

Saturday, July 12, 2014

Is Java “pass-by-reference” or “pass-by-value”?

Java is always pass-by-value. !!!!

However there is a difficulty in understanding this or more over a confusion when we are dealing with method calls involving Java Objects.

Java Specification says that everything in Java is pass-by-value and there is nothing called "pass-by-reference" in Java. To understand more about this, we can start with Java Object and reference understanding. Say we have a class called Employee

public class Employee
{
     private int id;
     private int age;
     private String name;

    // Getters-Setters ...

}

Now we will create an object instance of Employee as below

    Employee myEmp = new Employee();

Here myEmp is not "Employee" but a handle to point to an instance of "Employee" object somewhere sitting in memory.



We have a method call handleEmployee as below which needs Employee object

public void handleEmployee(Employee emp)
{
     // Do Something with employee
    
}

When we call the above method as below
  

      Employee myEmp = new Employee();
      handleEmployee(myEmp);

What essentially happens here is that, we are passing a copy of the handle (myEmp) which was used to access Employee object to the calling method.


Why java pass-by-value ?

Because, we as passing a copy of a reference variable - myEmp, to handleEmployee method ( as emp).

This gives the method handle to get to Employee object but it cannot change myEmp reference itself.

public void handleEmployee(Employee emp)
{
     // Do Something with employee
     emp = null;
}

When we make emp = null, then it just nullifies the copy so that it will no longer refer Employee object. But the original myEmp is still unaffected.

So, as a conclusion, Java is always "pass by value" whether we are passing primitives ( int, char, long, etc) or an object.


Unit Testing - Test Private methods using JUnit

Unit testing is a very critical and crucial part of any development activity. Simple but sound unit test cases can save many hours of debugging time for a developer which indeed improves the code quality. For a Java developer, Junit is one of the old and preferred way of fortifying his code. 

During unit testing, we often need to test a class completely which includes testing individual private methods for proper bug free execution which covers all corner case. Below is description on how we can test a private method using JUnit.

Class targetClass = MyClassWithPrivateMethod.class;
Object[] myMethodArgsClasses = new Object[]
              {MethodArgType1.class,MethodArgType2.class,...}
Method method = targetClass.getDeclaredMethod(methodName,
                 myMethodArgsClasses);
method.setAccessible(true);
method.invoke(targetObject, argObjects);
// More testing goes here

Monday, December 16, 2013

Static class in Java


June 16, 2013
Can a class be static in Java ?
The answer is YES, we can have static class in java. In java, we have static instance variables as well as static methods and also static block. Classes can also be made static in Java.
Java allows us to define a class within another class. Such a class is called a nested class. The class which enclosed nested class is known as Outer class. In java, we can’t make Top level class static.Only nested classes can be static.
What are the differences between static and non-static nested classes? 
Following are major differences between static nested class and non-static nested class. Non-static nested class is also called Inner Class.
1) Nested static class doesn’t need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.
2) Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.
3) An instance of Inner class cannot be created without an instance of outer class and an Inner class can reference data and methods defined in Outer class in which it nests, so we don’t need to pass reference of an object to the constructor of the Inner class. For this reason Inner classes can make program simple and concise.
/* Java program to demonstrate how to implement static and non-static
   classes in a java program. */
class OuterClass{
   private static String msg = "GeeksForGeeks";
    
   // Static nested class
   public static class NestedStaticClass{
      
       // Only static members of Outer class is directly accessible in nested
       // static class
       public void printMessage() {
         // Try making 'message' a non-static variable, there will be
         // compiler error 
         System.out.println("Message from nested static class: " + msg);
       }
    }
    
    // non-static nested class - also called Inner class
    public class InnerClass{
        
       // Both static and non-static members of Outer class are accessible in
       // this Inner class
       public void display(){
          System.out.println("Message from non-static nested class: "+ msg);
       }
    }
}
class Main
{
    // How to create instance of static and non static nested class?
    public static void main(String args[]){
        
       // create instance of nested Static class
       OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass();
        
       // call non static method of nested static class
       printer.printMessage();  
  
       // In order to create instance of Inner class we need an Outer class
       // instance. Let us create Outer class instance for creating
       // non-static nested class
       OuterClass outer = new OuterClass();       
       OuterClass.InnerClass inner  = outer.new InnerClass();
        
       // calling non-static method of Inner class
       inner.display();
        
       // we can also combine above steps in one step to create instance of
       // Inner class
       OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
        
       // similarly we can now call Inner class method
       innerObject.display();
    }
}
Output:
Message from nested static class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks