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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With