Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many imports spamming my code

Tags:

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?

like image 584
ApprenticeHacker Avatar asked Dec 13 '11 07:12

ApprenticeHacker


People also ask

Why is it better to avoid * in import statements in Java?

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.

Why should we avoid wildcard imports?

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.

Does Import make my class bigger?

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.

Which of the following wildcard character is used to import all the classes in a particular package?

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.


1 Answers

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

like image 79
Bjorn Reppen Avatar answered Sep 28 '22 04:09

Bjorn Reppen