patternjavaCritical
What are the dangers of using a wild card with a Java import statement?
Viewed 0 times
withwildarejavastatementdangerstheusingcardwhat
Problem
It is much more convenient and cleaner to use a single statement like
than to import a bunch of individual classes
What are the dangers with using a wildcard in the
import java.awt.*;than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...What are the dangers with using a wildcard in the
import statement?Solution
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
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 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.
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:- You have an outright naming conflict between
java.awt.Eventandcom.mycompany.calendar.Event, and so you can't even compile.
- 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.
- 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 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.
Context
Stack Overflow Q#147454, score: 750
Revisions (0)
No revisions yet.