What is the proper style for listing imports in Java?

前端 未结 10 1037
梦谈多话
梦谈多话 2021-02-18 16:01

Is it better to list each individual piece of a package you\'re going to need (see #1) or is it better to just import everything from a package (see #2)?

1



        
10条回答
  •  感动是毒
    2021-02-18 16:06

    I know the question was not about performance but, the cost of import statements question of the month on javaperformancetuning.com perfectly summarize why you should avoid to use wildcards:

    (...) Finally, many people find that using imports with wildcards makes the source much less readable, since the reader also needs to figure out which package a particular class comes from, rather than just looking it up in the import statement.

    So the full answer is

    • There is no runtime cost from using an import statement
    • The compilation process can take a little more time with an import statement
    • The compilation process can take even more time with a wildcard import statement
    • For improved readability, wildcard import statements are bad practice for anything but throwaway classes
    • The compilation overhead of non-wildcard import statements are minor, but they give readability benefits so best practice is to use them

    It is a bad practice to use wilcard import statements, they make the code less readable, just don't do it. The only exception to this rule are static import, for example import static org.junit.Assert.*;. No, I don't want to import each assertXXX individually and I don't find that this harms code readability.

提交回复
热议问题