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

后端 未结 17 1638
梦谈多话
梦谈多话 2020-11-21 13:07

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

import java.awt.*;

than to import a bunch of individual classes

17条回答
  •  忘了有多久
    2020-11-21 13:49

    1. It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
    2. It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
    3. It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
    4. The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.

    Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.

提交回复
热议问题