Pitfall - Wildcard imports can make your code fragile

suggest change

Consider the following partial example:

import com.example.somelib.*;
import com.acme.otherlib.*;

public class Test {
    private Context x = new Context();   // from com.example.somelib
    ...
}

Suppose that when when you first developed the code against version 1.0 of somelib and version 1.0 of otherlib. Then at some later point, you need to upgrade your dependencies to a later versions, and you decide to use otherlib version 2.0. Also suppose that one of the changes that they made to otherlib between 1.0 and 2.0 was to add a Context class.

Now when you recompile Test, you will get a compilation error telling you that Context is an ambiguous import.

If you are familiar with the codebase, this probably is just a minor inconvenience. If not, then you have some work to do to address this problem, here and potentially elsewhere.

The problem here is the wildcard imports. On the one hand, using wildcards can make your classes a few lines shorter. On the other hand:

The lesson is that it is a bad idea to use wildcard imports in code that needs to be long lived. Specific (non-wildcard) imports are not much effort to maintain if you use an IDE, and the effort is worthwhile.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Pitfalls - language syntax:
* Pitfall - Wildcard imports can make your code fragile

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
108 Pitfalls - language syntax
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap