为什么使用带有Java import语句的外卡不好? [英] 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;
...
在 import
声明?
推荐答案
唯一的问题是它会使你的本地命名空间变得混乱。例如,假设您正在编写Swing应用程序,因此需要 java.awt.Event
,并且还要与公司的日历系统连接,该系统具有 com.mycompany.calendar.Event
。如果使用通配符方法导入两者,则会发生以下三种情况之一:
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:
-
java.awt.Event
和com.mycompany.calendar.Event
,所以你甚至无法编译。 - 你实际上只管理导入一个(两个导入中只有一个导入
。*
),但这是错误的,你很难弄清楚为什么你的代码声称类型错误。 - 编译代码时没有
com.mycompany.calendar.Event
,但是当他们以后添加一个你以前有效的代码突然停止编译。
- You have an outright naming conflict between
java.awt.Event
andcom.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 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.
这篇关于为什么使用带有Java import语句的外卡不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!