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?
Wildcard imports tell java compiler to search for class names in the given package. Hence, using wild card imports, the compile-time performance may lower a bit.
Wildcard imports help us avoid a long list of imports in our code. Therefore, this impacts the readability of code as the reader may have to scroll a lot in every source code file before reaching the code that shows the logic.
Import statement doesn't make your class bigger. Why because, importing a class means that to tell the compiler to load the specified class into memory during compilation.
Importing an Entire Package To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character. Now you can refer to any class or interface in the graphics package by its simple name.
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
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