Java Reference
In-Depth Information
Another exception is the finalize() method in java.lang.Object() . Don't use it. It isn't
guaranteed to be invoked, but because it might get invoked, it will cause your dead objects
not to be garbage collected, resulting in a memory leak. If you need some kind of cleanup,
you must take responsibility for defining a method and invoking it before you let any object
of that class go out of reference. You might call such a method cleanUp() . For application-
level cleanup, see Using Shutdown Hooks for Application Cleanup .
Generalize
There is a trade-off between generality (and the resulting reusability), which is emphasized
here, and the convenience of application specificity. If you're writing one small part of a very
large application designed according to OO design techniques, you'll have in mind a specific
set of use cases. On the other hand, if you're writing “toolkit-style” code, you should write
classes with few assumptions about how they'll be used. Making code easy to use from a
variety of programs is the route to writing reusable code.
Read and write javadoc
You've no doubt looked at the Java online documentation in a browser, in part because I just
told you to learn the API well. Do you think Sun/Oracle hired millions of tech writers to pro-
duce all that documentation? No. That documentation exists because the developers of the
API took the time to write javadoc comments, those funny /** comments you've seen in
code. So, one more bit of advice: use javadoc. The standard JDK provides a good, standard
mechanism for API documentation. And use it as you write the code—don't think you'll
come back and write it in later. That kind of tomorrow never comes.
See Documenting Classes with Javadoc for details on using javadoc.
Use subclassing and delegation
Use subclassing. But don't overuse subclassing. It is one of the best ways not only for avoid-
ing code duplication, but for developing software that works. See any number of good books
on the topic of object-oriented design and programming for more details.
There are several alternatives. One alternative to subclassing is delegation. Think about “is-
a” versus “has-a.” For example, instead of subclassing NameAndAddress to make Supplier
and Customer , make Supplier and Customer have instances of NameAndAddress . That is a
clearer structure; having a supplier be a NameAndAddress just because a supplier has a
name and address would not make sense. And delegation also makes it easier for a Customer
to have both a billing address and a shipping address. Another alternative is aspect-oriented
Search WWH ::




Custom Search