The original article is addressed in JavaWorld: Why extends is evil.
The extends keyword is evil, maybe not at the Charles Manson Level, but bad enough that it should be shunned whenever possible. The Gang of Four Design Patterns book discusses at length implementation inheritance (extends) with interface inheritance(implements).
Good designers write most of their code in terms of interfaces, not concrete base classes. This article describes why designers have such odd habits, and also introduces a few interface-based programming basics.
Interface versus classes
Losing flexibility
Why should you avoid implementation inheritance? The first problem is that explicit use of concrete class names locks you into specific implementations, making down-the-line changes unnecessarily difficult.
Many successful projects have proven that you can develop high-quality code more rapidly ( and cost effectively ) this way than with the traditional pipelined approach.
Rather than implement features you might need, you implement only the features you definitedly need, but in a way that accommodates change.
A better solution to the base-class issue is encapsulating the data structure instead of using inheritance.
Summing up fragile base classes
In general, it is best to avoid concrete base classes and extends relationships in favor of interfaces and implements relationships. My rule of thumb is that 80 percent of my code at minimum should be written entirely in terms of interfaces. I never use references to a HashMap, for example; I use references to the Map interface.(I use the word "interface" loosely here. An InputStream is effectively an interface when you look at how it's used, even though it's implemented as an abstract class in Java.)
The more abstraction you add, the greater the flexibility. In today's business environment, where requirements regularly change as the program develops, this flexibility is essential. Moreover, most of the Agile developement methodologies simply won't work unless the code is written in the abstract.
If you examine the Gang of Four patterns closely, you'll see that many of them provide ways to eliminate implementation inheritance, and that's a common characteristic of most patterns. The significant fact is the one we started with: patterns are discovered, not invented. Patterns emerge when you look at well-written, easily maintainable working code. It is telling that so much of this well-written, easily maintainable code avoids implementation inheritance at all cost.
Wednesday, November 26, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment