Thursday, November 20, 2014

Identifiers and limit on Identifier length in Java (maximum length of Class,interface, package, method, variable names).

Fun time.

Though it is not a big thing to consider, yet out of curiosity one can interested to know about the limit on Class names, Interface names, Package names, Variables names, Method names etc.

Before going to start with that let me introduce the term identifier . What is it? The above all names so far we mentioned (Class, Interface, Package, Method, Variable names) are identifiers. Do not confuse with the terms literal and identifier and literal. Definition given by Oracle for Identifier is

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7).

And the rules to remember while writing and identifiers is,

Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.

class Hummingbird {  
      public static void main(String[] args) {  
           System.out.println("Java Identifiers");  

Considering above piece of code, HummingbirdmainStringargsSystem, outprintln are identifiers. And if we see carefully, from the definition there is no limit on their names. So the length is unlimited. But there is a small and important things to remember here.

  • The language specification have no limit, but JVM may have limit on it.
  • It depends on underlying Operating System as well, since the OS may have restriction on file name where SomeLongestJavaFileName.Java may cross the limit if OS file name length.

And some class names I found personally on internet are (source) (source)

But apart from fun, follow proper naming conventions and don't care how big it is, just name it. That helps lot for the future readers of your code.

Wednesday, November 5, 2014

Why GWT loads slow and tips to load GWT app faster.

Why GWT loads very slow for first time:

GWT uses perfect caching technique. The initial loading time is really depends on many factors.

When user/browser requests for the very first time, all the resources related to the page loads. That takes few seconds to load and really depends on your internet speed. Once the complete page loaded and if you are requesting new page/ reloading the current page, all the resources won't load this time.

Coming to the part that rebuilding and recompiling for each request is wrong. In Gwt there are permutations which are specific to each browser. Every major browser have it's own permutation. If you request from Mozilla for example, permutations related to Mozilla loads. These permutations actually generates at compile time of project which you done in your IDE before deploying the project.

Once the request hit the browser, for very first time these all files related to the specific permutation loads into browser and ***cached*** in browser. Form next time on words you won't see any new files loading in to browser (you can see that using your firebug). That way caching works. Below shows steps to load GWT app faster.

Other than the above behavior of GWT, from your side also more damage can happen. For ex, Adding more code in onModuleLoad() method, loading your all data at first shot, poor layout design, lastly wrong usage of Java classes.

How to load GWT app faster: 

The Official Docs came up with some bullet points

1) Look into Code Splitting. Break your service requests in to chunks.

2) As much as you can reduce the load in onModuleLoad(),That's greatly helps you to bring the app to client much faster. 

3) Show minimal data. Use pagination techniques. Never load all the records in a grid/table for first time.

4) Lazily load your Widgets. That increases DOM performance and DOM loading time.

5) Analyze Compile Time Reports helps you greatly where you are digging too much into Object.

6) Enable the Gzip for your server,Which compresses the data in Gzip format to client. That reduces the page load.

7) Learn standard java coding techniques(respective to GWT-RPC) while coding. Use an ArrayLists instead of Lists, HashMap's instead of Map's then GWT compiler does not need to compile the code for all possible implementations of the List,Map's etc. Use StringBuilders instead of String's. ..etc

8) Enable compression.

9) Remove unused CSS.

10) Minify JavaScript, CSS, HTML.

11) Deferred loading of JavaScript.

12) Optimize images.

12) Serve scaled images.

13) Serve resources from a consistent URL.
And some more techniques here Google I/O presentation by Ray Rayan

After you started doing the above techniques, you can constantly check the difference in page loading by install some plugin into browser like

For Chrome : PageSpeed Insights (by Google)

Note: Using above techniques I increased my page speed upto 60-70%. Others, please come up with your own techniques to share with world. 

Tuesday, November 4, 2014

Covariant, Contravariant and Invariant (class invariant) in Java

Type variance is another feature which defines the flexibility in code writing every of programming language. Let me show you some of the variant type jargon's which explains the type variance.

(Copyrights of image belongs to :

When ever we are talking about type variance, we end up with explaining about sub-typing which is again inheritance. Because the above stated jargon's Covariant, Contravariant can clearly explain only with sub-typing and we use there terms in the context of Overloading and overriding Sticking to one language, examples shown below explains Covariance,Contravariance in Java. We will discuss Invariance later. The basic principle of there type variance is (quote from wikipedia)

If Cat is Subtype of Animal, then an expression of type Cat can be used whenever an expression of type Animal could.

Based on the above principle let see how the type has been divided and what actually it is.


Consider you have Parent and Child relationship and trying to override the methods of Parent in Child, Co-variance means that the overriding method returning a more specific type. Below example shows you the same, Parent method returning Object and where as the Child method decided to return a specific type (String) where String is child of Object class. Hence covariance existed here.

Covariant return type :

public class Parent{  
  public Object doSomething(){}  
 public class Child extends Parent{  
  public String doSomething() {}  

Covariant arg type :

public class Codeinventions {  
      public static void print(Object[] arg) {  
           for (Object object : arg) {  
      public static void main(String[] args) {  
           String[] strs = { "Java", "Codeinventions" };  
 Result :  

So, it is clear that we can pass a Sub-type where a Parent needed, since Every Child is a Parent. Yes Java supports it. And the same logic works in Generics as well.


Contravariance is just reverse to Covariance. Passing exact type to the required place. There will be no flexibility in coding. But useful to avoid run time problem since you are being forced to stick to the exact type.

When you want to pass a Parent where Child is required, that's Contravariance and many languages won't allow you to do it. At least in Java I can confirm you that, it is not allowed to do so. Look at the Contravariance shown in below, and you end up with the error "The method print(String) in the type ParentClass is not applicable for the arguments (Object)". 
public class ParentClass {  
      public static void print(String str) {  
      public static void main(String[] args) {  
           Object str = "Codeinventions";  
           print(str);  //compiler error here 
Form the compiler error shown above, there is no way of supporting Contravariance in Java.

Invriant (class invariant):

Invariant  or variance is something which is always true no matter what the context is. 

Variant or Variance is not just a unchanged variable it's more of a term which used to represent something which never changed what so ever it's context, Let me explain you the same with respect to Java with help of a Class called as Class Invariance. Consider there is a class called  Account and have a holder in itNow, Invariance or Class Invariance is, no matter where the Account being use in the program the state of the invariant holder will be satisfies some conditions(always true) at any context. That's the design decision to make which variable is invariant in the program. 
 Class Account {  
 private AccountHolder holder = new AccountHolder();  
If you see in the above code making  holder an invariant mean that no matter what the state of Account, my holder always holds some properties which are never be changed in normal conditions. May change in special conditions but with notifying to the owner.

There invariant's are useful or comes into picture while designing the program and for programmers while debugging the program. Consider at some point you are getting some weird results from a method and trying to debug your program, the basic principle you need to apply is see any invariant's are gone change and proceeding your debug keeping in mind these class invariant's so that it makes your debug easy as well.

Monday, October 13, 2014

Programming with interface and programming to interface

Another good habit that every programmer adopt is programming to interfaces, rather than programming to implementations. It is clearly not about using interfaces in your application, though you are using interfaces at design level, it is very hard to make coders to get benefit out it. There is a very big difference between programming with interfaces and programming to interfaces. The main difference is that
  • programming with interfaces -design level
  • programming to interfaces -coding level

To understand what I exactly mean, just look into the below example.

 interface Animal {  
   public void eat();  
 class Human implements Animal{  
   public void eat(){  
     // Eat cakes and Buns   
 class Dog implements Animal{  
   public void eat(){  
     // Eat bones   
If you see the above code, we just took an interface called Animal and designed another two classes by implementing the same interface. Let's now discuss where exactly the two sentences programming with interfaces and programming to interfaces comes into picture.

Programming with Interfaces :

Keeping the above code in mind, at design level (before start coding) itself one must decide weather to use interfaces or not based on the business logic. In the above example I decide to place an interface called Animal and I'll put all the common functionality in the interface. Later if you are saying that your class is said to be an Animal, you class must implement my Animal interface. Later I'l use that Interface to write my generic methods, and to create generic functionality. For ex, I can create methods like this
public makeAnimalEat( Animal animal ) {;   
 Dog dog = new Dog();  
 //since every Dog implement interface, it is allowed to pass Dog to that method.
Another method to make a group eat,
public static makeAllAnimalsEat( List<Animal> animals ) {  
  for (Animal animal : animals) {;  
In above methods (instance or static methods) though you are not aware of what type of animal being passed to the method, you can still make the Animal eat. The above shown methods are just small examples and like wise you can create much more complex functionality with simple effort of making/planning your functionality with Interfaces. This is exactly programming with interfaces. When ever there is a possibility, go ahead and use Interface instead a Class so you won't end up in writing different methods for different Classes.

Programming to Interfaces :

The concept of programming to interface comes in to picture only at the time of creating/instancing of object. Consider you are writing code to create Room in Zoo. Each room have an Animal inside it. Let's call it as a DogRoom.
public class AnimalRoom {  
 // creating an animal inside Room  
 Dog dog = new Dog();  
 // play with dog  
The above code works fine and you need not worry about it. Problem arises when you planning to change the type of Animal inside the room. For example you are planning to change to a Cat. Then if you are writing Dog dog = new Dog() and when you want to change it to Cat , you have to check/change all the methods/variables of Dog to Cat. But if you program to interface 
Animal animal = new Dog();  
// play with animal here  
When ever you need to change just change the Right Hand Side of the initialization part and you are done without any code breakage and without any compiler error.
Animal animal = new Cat();  
// play with animal here 
You are just done. Nothing to change other than that initialization part. That is what exactly programming to interface.

Wednesday, October 8, 2014

NoSuchMethodException vs NoSuchMethodError in Java

As we all know that there is a clear difference between Exception and Error. You can recover from an Exception but cannot from an Error. That's the basic difference. Coming to our actual problem which related to NoSuchMethod, we have NoSuchMethodException and NoSuchMethodException. Let us see, when and why occurs what.


This exception occurs when you try to access a method which is not present in the class. Consider there is a Class called Consumer. And Consumer calling a method called sellMe() of Class Buyer which is not actually presented in Buyer class. If you are calling normally invoking this, an compile time occurs, Normally in the sense without using reflection .

If you are using reflection and trying to invoke a method using reflection like below, there are chances to get NoSuchMethodException, if your Buyer class doesn't have sellMe() method. 
Class b = Class.forName("");  
           try {  
                Method m = b.getDeclaredMethod("sellMe", params);  
           } catch (NoSuchMethodException e) {  
Since that is a Exception you can simply catch it and can proceed with your flow, where as it is not possible with NoSuchMethodError.


This error occurs when there is a method missing at run time from the other class where the method actually there while you are compiling. Confused ? Let see with an example. 

Consider you have 2 classes, Consumer and Buyer. From Consumer you called a method of Buyer using it's instance. Later you removed the method from Buyer and compile the Buyer alone. So now Consumer messed up right?, which is still trying to refer the method sellMe(). Yes it is.

You just the changed/removed a method of Buyer , where the Consumer don't know about this change and still using the same. Hence the Error arises. Usually we run into this error in cases like we are using a third party library or jar that depends on another jar. Where the first jar invoking a method in second second jar which is not at all present because of incompatible versions. Keeping the compatible versions of jar's removes the error.