Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using a wild card with a Java import statement bad?

It is much more convenient and cleaner to use a single statement like

import java.awt.*; 

than to import a bunch of individual classes

import java.awt.Panel; import java.awt.Graphics; import java.awt.Canvas; ... 

What is wrong with using a wildcard in the import statement?

like image 913
jnancheta Avatar asked Sep 29 '08 03:09

jnancheta


People also ask

Do wildcard imports affect performance?

There is no performance difference between a specific import and a wildcard import declaration. The information for the classes in imported package is not read in at compile time or run time unless the class is used in the program.

Why are wildcard imports bad python?

import * ) When an import statement in the pattern of from MODULE import * is used it may become difficult for a Python validator to detect undefined names in the program that imported the module.

Do imports slow down Java?

No. Imports are purely a compile time construct ... syntactic sugar. The imports tell the Java compiler how to map identifiers in the source code to fully qualified class names.

What are specific and wildcard imports?

Specific imports are hard dependencies, whereas wildcard imports are not. If you specifically import a class, then that class must exist. But if you import a package with a wildcard, no particular classes need to exist. The import statement simply adds the package to the search path when hunting for names.


1 Answers

The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:

  1. You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
  2. You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
  3. When you compile your code there is no com.mycompany.calendar.Event, but when they later add one your previously valid code suddenly stops compiling.

The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.

like image 64
Benjamin Pollack Avatar answered Sep 20 '22 23:09

Benjamin Pollack