Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android efficiency importing static methods or importing the class

I've seen in some projects people importing directly a static method into an Activity or a class instead of the whole class.

My question is, knowing that a static method can be called several times (for being more accurate, 5 or more times) in the same class, is it more efficient to import the static method or it is better to call it through its class?

like image 788
Jose M Lechon Avatar asked Feb 20 '15 16:02

Jose M Lechon


People also ask

Why should we avoid static imports?

If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from.

Are static imports good?

Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

What is the advantage of static import in Java?

The import allows the java programmer to access classes of a package without package qualification. The static import feature allows to access the static members of a class without the class qualification.

Why are static imports bad Java?

by Joshua Bloch.) This is considered bad Java programming practice because when a class implements an interface, it becomes part of the class's public API. Implementation details, such as using the static members of another class, should not leak into public APIs.


1 Answers

Your question (according to me) does seems to address the same point. The question is if: is calling ClassName.staticMethod() directly

or this

import static ClassName.staticMethod;
//rest of the stuff
staticMethod();

In both cases, the methods are loaded as a singleton whenever the class is called first.If you import the static method,then thats the first time or else when you use the class's method.

So it wont make a difference because the JVM/DVM (not sure about ART) already has the data required.

IF however your question is regarding what modifiers to use,then this advocates static.

But as mentioned,involving static methods directly is just messy. So now its more of a personal choice. Read as:Do not import static methods directly unless you have a very specific reason to do so.

like image 195
Droidekas Avatar answered Sep 20 '22 05:09

Droidekas