Saturday, March 5, 2011

Why Avoid Wildcard Import Statements?

A few years ago, all the open source projects switched to importing every class that is used outside of the current class’ package. The problem was that I didn’t find a lot of talk about why this had been mandated.  

I had heard that it optimizes java compiler build time, but frankly, compilation of my largest project on modern machines was a matter of seconds.  (Now unit testing time, on the other hand… that’s another story… but I digress!)

So  at first I didn’t necessarily buy the concept of requiring per-class imports instead. In fact, it is easier to trace package-level dependencies by using wildcard imports since it results in a cleaner import list.  So I personally thumbed my nose at the standard for a while.

However, one day I finally saw the light.

Consider the following class:

import org.example.package1.*;
import org.example.package2.*;
import org.example.package3.*;
import org.example.package4.*;

public class Example {
public ServiceOne one;

public ServiceTwo two;
}

It’s a simple enough class, but given the imports where did ServiceOne and ServiceTwo come from? If you had the source code in your IDE, it would be very simple to do – tell the IDE to find the service’s declaration.

But what about inside a web browser?

Or text editor?

What about a situation where your IDE can’t compile enough code to tell you where ServiceOne and Service Two came from?

There are many instances when reading code where you will have the given class open in either a straight text editor or a web browser. This is especially true when browsing a code repository online. 

So it comes down to the fact that using wildcard import, it is impossible to find out where ServiceOne and ServiceTwo came from:

import org.example.package1.Fwibble;
import org.example.package2.ServiceOne;
import org.example.package3.Fwobble;
import org.example.package4.ServiceTwo;

public class Example {
public ServiceOne one;

public ServiceTwo two;
}


Now we know where to look!



Furthermore, thanks to modern IDE’s, it is extremely simple to add imports while you are typing.  (Ctrl-1 in Eclipse). 


If, like myself, you haven’t found the whole “avoid wildcard imports” argument.

No comments:

Post a Comment