Too many imports spamming my code

江枫思渺然 提交于 2019-12-04 00:33:31

Yes, too many imports is a bad thing because it clutters your code and makes your imports less readable.

Avoid long import lists by using wildcards.

Kevlin Henney talks about this exact Stack Overflow question 27:54 into his presentation Clean Coders Hate What Happens to Your Code When You Use These Enterprise Programming Tricks from NDC London 16-20 Jan 2017

stivlo
  • It's a good practice to import class by class instead of importing whole packages

  • Any good IDE, such as Eclipse, will collapse the imports in one line, and you can expand them when needed, so they won't clutter your view

  • In case of conflicts, you can always refer to fully qualified classes, but if one of the two classes is under your control, you can consider renaming it. (with Eclipse, right click on the class, choose Refactor -> Rename, it will take care to update all its references).

  • If your class is importing from AWT and from your package of shapes, is ok. It's ok to import from several classes; however, if you find yourself importing from really lots of disparate sources, it could be a sign that your class is doing too much, and need to be split up.

Another alternative is to type the fully qualified class name as you need it. In my example, there are 2 Element object, one created by me org.opensearch.Element and the other org.w3c.dom.Element.

To resolve name conflict, as well as to minimize import "clutters", I've done this (in my org.opensearch.Element class):

public org.w3c.dom.Element toElement(org.w3c.dom.Document doc) { /* .... */ }

As you can see, the return Element type is fully-typed (i.e. I've specified the fully-qualifed class name of Element).

Problem solved! :-)

Hurda

It's normal in Java world to have a lot of imports - you really need to import everything. But if you use IDE such as Eclipse, it does the imports for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!