Wednesday, September 29, 2004
Java imports
Here's an aspect of Java imports that I've gone back and forth on. Now I'm firmly in one camp and thought I'd post about it.
An explicit import in Java does a couple of things. First it provides a short name for a class in another package (e.g. List rather than java.util.List). Second, it documents an external dependency (e.g. this class uses java.util.List). This is great and so much nicer than the "header file hell" of C/C++.
But what does a wildcard import mean? (e.g. import java.util.*;). It's intended as a convenient way to avoid multiple import statements but it introduces ambuguities with duplicate short names. For example, if I import java.util.* and java.awt.*, which List class I get depends on the order of the import statements. This doesn't work well as packages evolve. Code that compiles today may break tomorrow. Second, it doesn't properly document which classes from these packages I actually use. So I do not use wildcard imports. This isn't as onerous as it may sound. Here's why:
An explicit import in Java does a couple of things. First it provides a short name for a class in another package (e.g. List rather than java.util.List). Second, it documents an external dependency (e.g. this class uses java.util.List). This is great and so much nicer than the "header file hell" of C/C++.
But what does a wildcard import mean? (e.g. import java.util.*;). It's intended as a convenient way to avoid multiple import statements but it introduces ambuguities with duplicate short names. For example, if I import java.util.* and java.awt.*, which List class I get depends on the order of the import statements. This doesn't work well as packages evolve. Code that compiles today may break tomorrow. Second, it doesn't properly document which classes from these packages I actually use. So I do not use wildcard imports. This isn't as onerous as it may sound. Here's why:
- I rarely type import statements anyway. I let Eclipse handle them for me. Eclipse does a much better job of managing and organizing imports automatically than I can.
- The Eclipse 3.0 Java editor automatically folds imports so that I don't have to look at them if I don't want to.
- A class with dozens and dozens of import statements may indicate too much coupling of classes and may need refactoring.
- Explicit imports are easy to scan for using simple text tools. You won't catch classes that are dynamically loaded via Class.forName() but it will find everything else. This is a good thing.
RSS 0.92 Feed