Java Reference
In-Depth Information
package. You are also introducing extra dependencies into your code. Most of the time this
won't make any real difference, but when it does, it leads to problems that are hard to identify
and fix. Your code is also easier for others to read if you avoid importing entire namespaces,
since the reader can go to the top of a file and use the import statements to find our what
package contains the imported names for the file. This advantage is somewhat minimized by
the navigation functions in modern interactive development environments, but you can't yet
assume that all of your colleagues use such an environment. Be nice to those who don't; they
suffer enough as it is.
As a general rule, you are better off importing only those parts of another package that you
really need (and that you actually refer to) rather than the whole package. Modern IDEs make
this pretty straightforward, as they will import names automatically when they are used. If you
really do need to import all of the names defined in another package, you might want to think
about the design of your system, as you have two distinct packages that are so intertwined that
you should probably only have one (or you have missed the real line that should separate the
On rare occasions you will find yourself unable to import a name into a namespace. This
is when that name already occurs within that namespace. Importing in such a circumstance
would lead to an ambiguous name, so the name that occurs within the namespace wins. If
you really need to refer to something from a different package that has the same name as
something in the current package, you need to refer to the external entity using the full name
(that is, with the package name as a prefix). Sometimes this can't be avoided, especially when
you are using code written by someone else and he has picked all the good names.
What can be avoided is doing this to yourself. In our example, we have named our implement-
ation of the Batter interface the BatterImpl class. But we could simply name our imple-
mentation class the Batter class, and say (in our source):
public class Batter
implements com.oreilly.javaGoodParts.examples.statistics.Batter{
This would technically work, in the sense that it would compile. But it would also be very
confusing to anyone trying to read or learn the code. It will even be confusing to you at some
time in the future when you try to maintain or extend the code you originally wrote. Having
separate namespaces lets you do this, but just because you can do it doesn't mean that you
Search WWH ::

Custom Search