简体   繁体   中英

Namespacing imported libraries for clarity in Java

Is it possible to keep the namespace of the methods being imported in Java? I'm wondering from a technical and practical perspective.

For example, say I'm importing the spark library so I can use it's get() method, I might do something like

import static spark.Spark.*;

public static void main(String[] args) {
    get(....);
    // do stuff
}

For someone looking at this (especially when the project is much bigger and several things are imported), it's not immediately obvious where "get()" comes from. I'd love to be able to do something like this

import static spark.*;

public static void main(String[] args) {
    Spark.get(....);
    // do stuff
}

As you can see the get() call is now visually namespaced under Spark .

Is this generally seen as permissible, or are there drawbacks to this approach? If so, why is it that more projects don't use this approach?

Thanks!

In my opinion, it all depends on what you are using really - class name on static calls is ok, but it becomes problematic when you are using something VERY often - because then you cover the logic behind a fake feeling meaning.

Also I'd say get is a pretty damn bad name for static method - if method names have more meaning, then they become less dependent on class name - but here we are left with no choice when using frameworks.

First of all, the usage of static import in what you'd love to be able to do is incorrect. As is, it means import all static members of class spark , whereas spark is the package. Class Spark would be unknown and you get a compile error. Get rid of that static in the above, and you import all classes of spark package. You refer to the class members as ClassName.member , and the instance members as instanceName.member . Clash of class names themselves is rare. So, the scheme, as is, pretty readable and elegant. But if your code uses a lot of static members of an imported class, referring them by prep-ending the class name each time could be cumbersome etc., so we have the short-cut way of static import. And the Java documentation has a nice advice on this, which perhaps answers your question.

... So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM