Is it wrong to import unused packages?

For example, when you are working as a team in a single file and have only a partial understanding of the various imported packages required for the code to work. Because of this, you change the code in this file and find that some code becomes redundant. You remove this part and now you don't know if the whole code still depends on all packages or not.

[Of course, the bad can be objectified in different ways: speed, readability, etc.)

+3


source to share


3 answers


Yes. For two reasons:

  • This can be confusing for the person looking at the code, seeing the imports that may or may not be used.
  • Import conflicts may occur with multiple classes imported with the same name. This requires that all but one class names refer to their fully qualified name in code.


For these reasons, java will issue warnings if an import statement is not needed and the IDE has ways to automatically remove unused imports.

Notice I didn't mention the speed and performance changes, I think javac is smart enough not to use unnecessary imports, so the compiled class will be the same as if you didn't import it.

+5


source


If necessary, you should only use as few imports as possible and not use full package imports, for example java.util.*

. IDEs today typically support this through the "Organize Imports" operation, which removes unused imports.

If you have a bunch of unused imports and you change the code, chances are that you will add / change code that belongs to the classes covered by the unused imports . Then you will not notice that you accidentally used them, although this may not be your intention.

If you only have minimal imports, if you add code related to the new class, the compiler will immediately notify you showing errors and give you the option to choose which class you intend to use.



Also, if you use imports outside of what is currently specified in your program, you increase the likelihood of breaking your program for future Java releases or libraries you are using.

Example: If your program only uses java.util.HashSet

, but you are still importing java.util.*

, and you are using a different third party library from where you are importing from com.mylib.*

, your code may compile. If a third-party library adds a named class in a future version com.mylib.HashSet

, you may no longer compile the code because the compiler will be unable to determine which class you want to use (for example, java.util.HashSet

or com.mylib.HashSet

).
You only imported java.util.HashSet

and for example only com.mylib.SomeUtil

, firstly, your code will still compile with the new version of the third party library.

+3


source


Importing unused packages will NOT affect your speed as described here

However ... this makes your code difficult to read if you have useless packages imported. If you are using NetBeans, you can always remove unused imports with Ctrl + Shift + I.

+1


source







All Articles