Courtesy: Allen Holub
Why extends is evil
Improve your code by replacing concrete base classes with interfaces
extendskeyword 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 replacing implementation inheritance (
extends) with interface inheritance (
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.
Interfaces versus classes
I once attended a Java user group meeting where James Gosling (Java’s inventor) was the featured speaker. During the memorable Q&A session, someone asked him: “If you could do Java over again, what would you change?” “I’d leave out classes,” he replied. After the laughter died down, he explained that the real problem wasn’t classes per se, but rather implementation inheritance (the
extendsrelationship). Interface inheritance (the
implementsrelationship) is preferable. You should avoid implementation inheritance whenever possible.
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.
Peter Michaux explains:
The goal of Java’s