Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to import unused packages?

For instance when you work in a team at the same file and have only a partial understanding of the different packages imported needed for the code to work. You change some code in this file and find out some code become redundant because of that. You delete that part and now do not know if the whole code still depends on all packages or not.

[Of course bad can be objectified in many ways: speed, read-abilty etc.]

like image 528
Joop Avatar asked Dec 09 '22 05:12

Joop


2 Answers

Yes. For a couple of reasons:

  1. It can be confusing for a human looking at the code seeing imports that may or may not be used.
  2. There may be import conflicts with several classes imported with the same name. This will require all but one of the similar class names to be referenced by their full qualified name in the code.

For these reasons, java will emit warnings if an import statement isn't needed and IDEs have ways to automatically delete unused imports.

Note, I didn't mention speed or performance changes, I think javac is smart enough to know not to use any unneeded imports so the compiled class will be just as if you didn't import it.

like image 55
dkatzel Avatar answered Jan 03 '23 07:01

dkatzel


You should always only use as few of the imports as necessary, and don't use complete package imports like java.util.*. Today's IDE's usually support this with an "Organize Imports" operation during which unused imports are removed.

If you have bunch of unused imports and you modify the code, there is a chance you will add/change code that refers to classes which are covered by the unused imports. Then you won't notice that you accidentally utilized them even though that might not be your intent.

If you only have the minimum imports, if you add code that refers to a new class, the compiler will immediately notify you by showing errors, and giving you the possibility to choose which class you intend to use.

Also if you use imports beyond what is currently referenced in your program, you increase the chance to break your program for future releases of Java or the libraries you use.

Example: If your program only uses java.util.HashSet but you still import java.util.* and you use another 3rd party library from where you import com.mylib.*, your code might compile. If in a future release the 3rd party library adds a class named com.mylib.HashSet, you're code might not compile anymore because the compiler might not be able to tell which class you wanted to use (e.g. java.util.HashSet or com.mylib.HashSet).
Have you imported only java.util.HashSet only and e.g. com.mylib.SomeUtil in the first place, your code would still compile with the new version of the 3rd party lib.

like image 36
icza Avatar answered Jan 03 '23 06:01

icza