除了减少混乱之外,还有什么理由清理 Java 中未使用的导入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/979057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:49:07  来源:igfitidea点击:

Any reason to clean up unused imports in Java, other than reducing clutter?

javaeclipsecoding-styleimport

提问by Kip

Is there any good reason to avoid unused import statements in Java? As I understand it, they are there for the compiler, so lots of unused imports won't have any impacts on the compiled code. Is it just to reduce clutter and to avoid naming conflicts down the line?

是否有充分的理由避免在 Java 中使用未使用的 import 语句?据我了解,它们用于编译器,因此许多未使用的导入不会对编译后的代码产生任何影响。是否只是为了减少混乱并避免命名冲突?

(I ask because Eclipse gives a warning about unused imports, which is kind of annoying when I'm developing code because I don't want to remove the imports until I'm pretty sure I'm done designing the class.)

(我之所以这么问是因为 Eclipse 对未使用的导入给出了警告,这在我开发代码时有点烦人,因为我不想删除导入,直到我很确定我已经完成了类的设计。)

采纳答案by Janusz

I don't think that performance problems or something like that are likely if you are not removing the imports.

如果您不删除导入,我认为不会出现性能问题或类似问题。

But there could be naming conflicts, in rare cases like importing the list interface.

但是可能存在命名冲突,在极少数情况下,例如导入列表界面。

In Eclipse you can always use a shortcut (depends on OS - Win: Ctrl + SHIFT + Oand Mac: COMMAND + SHIFT + O) to organize the imports. Eclipse then cleans up the import section removes all the stale imports etc. If you are needing a imported thing again eclipse will add them automatically while you are completing the statement with Ctrl + SPACE. So there is no need in keeping unused code in you class.

在 Eclipse 中,您始终可以使用快捷方式(取决于操作系统 - Win:Ctrl + SHIFT + O和 Mac: COMMAND + SHIFT + O)来组织导入。Eclipse 然后清理导入部分,删除所有过时的导入等。如果您再次需要导入的东西,eclipse 将在您完成语句时自动添加它们Ctrl + SPACE。所以没有必要在你的类中保留未使用的代码。

As always unused code will distract you and other people while reading the code and leaving something in your active code because of maybe I need it later is mostly seen as bad practice.

一如既往,未使用的代码会在阅读代码时分散您和其他人的注意力,并在您的活动代码中留下一些东西,因为也许我以后需要它,这通常被视为不好的做法。

回答by Yishai

One would be that if you remove the class referenced by the import from the classpath, you won't get a silly compiler error that served no purpose. And you won't get false positives when you perform a "where used" search.

一种情况是,如果您从类路径中删除导入所引用的类,您将不会得到一个毫无意义的愚蠢的编译器错误。当您执行“使用地点”搜索时,您不会得到误报。

Another (but this would be very specific in nature) would be if the unused import had naming conflicts with another import, causing you to use fully qualified names needlessly.

另一个(但这本质上是非常具体的)是如果未使用的导入与另一个导入有命名冲突,导致您不必要地使用完全限定名称。

Addendum: Today the build server started failing compilation (not even test running) with an out of memory error. It ran fine forever and the check-ins didn't have any changes to the build process or significant additions that could explain this. After attempting to increase memory settings (this is running a 64 bit JVM on a 64 bit CentOS!) to something well beyond where the clients could compile, I examined the checkins one by one.

附录:今天,构建服务器开始因内存不足错误而导致编译失败(甚至没有测试运行)。它永远运行良好,并且签入没有对构建过程或可以解释这一点的重要添加进行任何更改。在尝试将内存设置(这是在 64 位 CentOS 上运行 64 位 JVM!)增加到远远超出客户端可以编译的范围之后,我一项一项检查了签入。

There was an improper import that a developer had used and abandoned (they used the class, auto-imported it, and then realized it was a mistake). That unused import pulled in a whole separate tier of the application which, while the IDE isn't configured to separate them, the build process is. That single import dragged in so many classes that the compiler attempted to compile without having the relevant dependent libraries in the classpath, that this caused so many issues that it caused the out of memory error. It took an hour to solve this problem caused by an unused import.

开发人员使用并放弃了不正确的导入(他们使用了类,自动导入了它,然后意识到这是一个错误)。未使用的导入将应用程序的整个单独层拉入其中,虽然 IDE 未配置为将它们分开,但构建过程是。单个导入拖了很多类,编译器试图在类路径中没有相关依赖库的情况下进行编译,这导致了很多问题,从而导致了内存不足错误。解决这个由未使用的导入导致的问题花了一个小时。

回答by duffymo

Warning? Ask Eclipse to automagically clean them up for you. That's what IntelliJ does. If it's smart enough to warn you, it should be smart enough to clean them up. I'd recommend looking for an Eclipse setting to tell it to stop being such a nag and do something.

警告?让 Eclipse 自动为您清理它们。这就是 IntelliJ 所做的。如果它足够聪明来警告你,它应该足够聪明来清理它们。我建议寻找一个 Eclipse 设置来告诉它不要再唠叨了,做点什么。

回答by Uri

From a purist point of view, any dependency is a "constraint" on the product and can thus cause maintenance problems later.

从纯粹主义者的角度来看,任何依赖都是对产品的“约束”,因此可能会导致以后的维护问题。

For example, let's assume that your program uses the class com.X.Y.Z.ObjectPool, and that later on you decide not to use it but never remove the import. If somebody else now wants to instantiate org.W.V.Y.ObjectPool and just refer to ObjectPool, they don't get any warning about it until somewhere down the line there's a casting problem or invocation problem.

例如,让我们假设您的程序使用类 com.XYZObjectPool,然后您决定不使用它但永远不会删除导入。如果其他人现在想要实例化 org.WVYObjectPool 并只引用 ObjectPool,他们不会收到任何警告,直到在线某处出现转换问题或调用问题。

This is, by the way, not an unrealistic scenario. Every time you had Eclipse ask you which specific version of X you wanted to import, and you picked one from among many packages, is a scenario where if you have had the import there you might have gotten the wrong choice without knowing about it.

顺便说一下,这并不是一个不切实际的场景。每次当您让 Eclipse 询问您想要导入哪个特定版本的 X 并且您从许多包中选择一个时,就会出现这样一种情况:如果您在那里进行了导入,您可能会在不知情的情况下做出错误的选择。

Either way, you can ask Eclipse to clean these up for you

无论哪种方式,您都可以要求 Eclipse 为您清理这些

回答by Michael Zilbermann

I read somewhere, some years ago, that every imported class would be loaded at runtime with the importing class. So removing unused, especially whole packages, would reduce memory overhead. Although I suppose that modern versions of java deal with that, so probably it is not a reason anymore.

几年前,我在某处读到,每个导入的类都将在运行时与导入类一起加载。因此删除未使用的包,尤其是整个包,将减少内存开销。虽然我认为现代版本的 java 处理这个问题,所以可能不再是一个原因。

And by the way, with eclipse you can use Ctrl+Shift+Oto organize imports, but you can also configure a "cleaner" that deal with such things (and many others) each time you save a java file.

顺便说一下,与Eclipse可以使用Ctrl+ Shift+ O,组织进口,但你也可以配置一个“干净”的那笔交易这样的事情(和许多其他)每次保存Java文件。

回答by OscarRyz

This has to do with clarity of the program useful for maintenance.

这与对维护有用的程序的清晰度有关。

If you had to maintain a program you'll find how useful is to have a single class import per line.

如果您必须维护一个程序,您会发现每行只导入一个类是多么有用。

Think about the following scenario:

考虑以下场景:

import company.billing.*;
import company.humanrerources.*;

// other imports 


class SomeClass {
      // hundreds or thousands of lines here... 
    public void veryImportantMethod() {
      Customer customer;
      Employee comployee;
      Department dept. 
      // do something with them
     }
 }

When you're bugfixing or maintaining piece of code ( or only reading it ) it is very helpful for the reader to know to which package do the classes used belong to. Using the wildcard import as shown above doesn't help for that purpose.

当您正在修复或维护一段代码(或仅阅读它)时,了解所使用的类属于哪个包对读者非常有帮助。使用如上所示的通配符导入无助于该目的。

Even with an IDE, you don't want to hover or jump to declaration and return, it is easier if you understand in terms of functionality what other packages and classes the current code depends on.

即使使用 IDE,您也不想悬停或跳转到声明和返回,如果您在功能方面了解当前代码所依赖的其他包和类,则会更容易。

If this is for a personal project or something small, it really doesn't matter, but for something larger that have to be used by other developers ( and maintained through the years ) this is a MUST HAVE.

如果这是用于个人项目或小型项目,那真的无关紧要,但对于其他开发人员必须使用(并经过多年维护)的较大项目,这是必须的。

There is absolutely no performance difference with any.

绝对没有任何性能差异。

回答by kukudas

For eclipse i use this: window -> preferences -> java -> editor -> save action -> check the checkbox for organize imports (there are a lot of other useful stuff there too, like formatting, making fields final and so on..). So when i save my file eclipse removes the unessacry imports for me. In my opinion, if you don't need something then remove it (or let it be removed by eclipse).

对于 Eclipse,我使用这个:窗口 -> 首选项 -> java -> 编辑器 -> 保存操作 -> 选中组织导入的复选框(那里还有很多其他有用的东西,比如格式化,使字段成为最终的等等。 .) 因此,当我保存文件时,eclipse 会为我删除 unnessacry 导入。在我看来,如果您不需要某些东西,则将其删除(或由 eclipse 将其删除)。

回答by John

FYI, This caught me out, as I didn't think organize imports actually removed unused imports, I thought it just sorted them.

仅供参考,这引起了我的注意,因为我认为组织导入实际上并没有删除未使用的导入,我认为它只是对它们进行了排序。

Automatically removing imports during a save operation caused me some grief when for example, during development or testing you have a problem and comment out some code, when you save it, the imports used by the commented out section of code are removed. Sometimes this is not a problem as you can undo (Ctrl+Z) the changes, but other times it is not so simple as you may have made other changes. I also had a problem where when I uncommented the code (I have previously commented out then saved, thus removing the imports for that code), it automatically tried to guess the imports that were needed and picked up the wrong ones (e.g I think I had a StringUtilsclass being used and it picked another one with the same name from the wrong library).

在保存操作期间自动删除导入给我带来了一些痛苦,例如,在开发或测试期间,您遇到问题并注释掉一些代码,当您保存它时,被注释掉的代码部分使用的导入将被删除。有时这不是问题,因为您可以撤消 ( Ctrl+ Z) 更改,但有时它并不像您进行了其他更改那么简单。我也有一个问题,当我取消注释代码时(我之前已经注释掉然后保存,从而删除了该代码的导入),它会自动尝试猜测所需的导入并选择错误的导入(例如,我认为我有一个StringUtils类正在使用,它从错误的库中选择了另一个同名的类)。

I prefer to manually organize imports rather than have it as a save action.

我更喜欢手动组织导入而不是将其作为保存操作。

回答by Madan Sapkota

There is no any performance impact, though for readability you can make it clean. Removing unused imports is quite simple in both Eclipse and IntelliJ IDEA.

没有任何性能影响,但为了可读性,您可以将其清理干净。在 Eclipse 和 IntelliJ IDEA 中删除未使用的导入非常简单。

Eclipse

Windows / Linux -   Ctrl+Shift+O

Windows / Linux -    Ctrl+ Shift+O

Mac -                       Cmd+Shift+O

苹果机 -                        Cmd+ Shift+O

IntelliJ IDEAor Android Studio

IntelliJ IDEAAndroid Studio

Windows / Linux -   Ctrl+Alt+O

Windows / Linux -    Ctrl+ Alt+O

Mac -                       Cmd+Alt+O

苹果机 -                        Cmd+ Alt+O

回答by Sharon

You could comment the unused import statements out and the warnings wont bother you but you can see what you had.

您可以将未使用的导入语句注释掉,警告不会打扰您,但您可以看到您拥有的内容。