Too many imports spamming my code

后端 未结 8 2632
既然无缘
既然无缘 2021-02-18 13:37

In my project I have a shapes package which has shapes I designed for my graphics program e.g Rectangle, Circle. I also have one or two more packages that have the

8条回答
  •  死守一世寂寞
    2021-02-18 13:50

    I use explicit imports, and have done so for many years. In all my projects in the last decade this has been agreed with team members, and all are happy to agree to to use explicit imports, and avoid wildcards. It has not been controversial.

    In favour of explicit imports:

    • precise definition of what classes are used
    • less fragile as other parts of the codebase changes
    • easier to code review
    • no guessing about which class is in which package

    In favour of wildcards:

    • less code
    • easier to add and maintain the imports when using a text editor

    Early in my career, I did use wildcard imports, because back then IDEs were not so sophisticated, or some of us just used text editors. Managing explicit imports manually is quite a bit of effort, so wildcard imports really help.

    However at least once I was bitten by the use of wildcard imports, and this lead be to my current policy of explicit only.

    Imagine you have a class that has 10 wildcard imports, and it compiles successfully. Then you upgrade 5 jar files to newer versions (you have to upgrade them all, because they are related). Then the code no longer compiles, there is a class not found error. Now which package was that class in? What is the full name of the class? I don't know because I'm only using the short name, now I have to diff the old and new versions of the jars, to see what has changed.

    If I had used explicit imports, it would be clear which class had been dropped, and what it's package was, and this which jar (by looking of other classed in that package) is responsible.

    There are also problems reading code history, or looking at historic merges. When you have wildcard imports there is uncertainty for the reader about which class is which, and thus what the semantics of the code changes are. With explicit imports you have a precise description of the code, and it acts as a better historical record.

    So overall the benefit of the small amount of extra effort to maintain the import, and extra lines of code are easily outweighed by extra precision and determinism given by explicit imports.

    The only case when I still use wildcards, is when there are more that 50 imports from the same package. This is rare, and usually just for constants.

提交回复
热议问题