Java Language Pitfall - Wildcard imports can make your code fragile


Example

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:

  • Upwards compatible changes to other parts of your codebase, to Java standard libraries or to 3rd party libraries can lead to compilation errors.

  • Readability suffers. Unless you are using an IDE, figuring out which of the wildcard imports is pulling in a named class can be difficult.

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.