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

后端 未结 11 1336
生来不讨喜
生来不讨喜 2020-11-28 06:34

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 o

相关标签:
11条回答
  • 2020-11-28 07:24

    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.

    0 讨论(0)
  • 2020-11-28 07:27

    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

    Windows / Linux -   Ctrl+Shift+O

    Mac -                       Cmd+Shift+O

    IntelliJ IDEA or Android Studio

    Windows / Linux -   Ctrl+Alt+O

    Mac -                       Cmd+Alt+O

    0 讨论(0)
  • 2020-11-28 07:32

    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.

    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.

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

    0 讨论(0)
  • 2020-11-28 07:33

    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.

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

    0 讨论(0)
  • 2020-11-28 07:38

    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).

    0 讨论(0)
提交回复
热议问题