1000 Java Tips ebook
Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!.
Q:Inheritance seems error-prone. How can I guard against these errors?
JavaFAQ Home » Java IAQ by Peter Norvig
Q:Inheritance seems error-prone.
can I guard against these errors?
The previous two questions show that a programmer neeeds to be very
careful when extending a class, and sometimes just in using a class
that extends another class. Problems like these two lead John
Ousterhout to say "Implementation inheritance causes the same
intertwining and brittleness that have been observed when goto
statements are overused. As a result, OO systems often suffer from
complexity and lack of reuse." (Scripting, IEEE Computer, March
1998) and Edsger Dijkstra to allegedly say "Object-oriented
programming is an exceptionally bad idea which could only have
originated in California." (from a collection of signature files). I
don't think there's a general way to insure being safe, but there are
a few things to be aware of:
- Extending a class that you don't have source code for is always risky;
the documentation may be incomplete in ways you can't foresee.
- Calling super tends to make these unforeseen problems jump out.
- You need to pay as much attention to the methods that you don't
over-ride as the methods that you do. This is one of the big
fallacies of Object-Oriented design using inheritance. It is true
that inheritance lets you write less code. But you still have to
think about the code you don't write.
- You're especially looking for trouble if the subclass changes the
contract of any of the methods, or of the class as a whole. It is
difficult to tell when a contract is changed, since contracts are
informal (there is a formal part in the type signature, but the rest
appears only in comments). In the Properties example, it is not clear
if a contract is being broken, because it is not clear if the defaults
are to be considered "entries" in the table or not.
This tip is reprinted on JavaFAQ.nu by by courtesy of
Peter Norvig I am
thankful for his important contributions to my site - 21 Infrequently Answered
Java Questions. Alexandre Patchine
Printer Friendly Page
Send to a Friend
Search here again if you need more info!