In my project I have a shapes
package which has shapes I designed for my graphics program e.g Rectangle, Circle. I also have one or two more packages that have the same names as java.awt
classes.
Now, since I do not want to rename every class in my code-base, to show my source files which class I mean when I , say, declare a new Rectangle, I need to either:
1- import the rectangle class explicitly, i.e import shapes.Rectangle
OR
2- import only the java.awt classes I need and not import java.awt.* which automatically includes the awt.Rectangle
Now the problem is that both ways result in a lot of importing, I currently have an average of 15-25 imports in each source file, which is seriously making my code mixed-up and confusing.
Is too many imports in your code a bad thing? Is there any way around this?
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
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! :-)
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.