I was reading Code Conventions for Java from http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#587.
In that, they have mentioned that we should avoid the use of objects to access a class variable or a method and should we use the class name instead.
Avoid using an object to access a class (static) variable or method.
Use a class name instead. For example:classMethod(); //OK AClass.classMethod(); //OK anObject.classMethod(); //AVOID!
Is there a particular reason for this in terms or performance or something else?
By class variables I assume you mean static variables.
The use of static variables/methods through instance variables should be avoided because it’s confusing to the reader. Since you can only use instances to access instance variables, reading a code that calls static methods through an instance can confuse the reader about what’s going on.
Image this case, with
Thread.sleep, which is a static method:Since the method is static and we are calling it through the class name, it’s intuitive to the reader to deduce that the effect is to put the current thread to sleep.
Now if we did this:
Now which thread is put to sleep? The current one “obviously”. Someone not knowing about how sleep works might think that the child thread is somehow put to sleep.