Re: Using abstract class that implements interface
On Sat, 18 Apr 2009, Lew wrote:
Tom Anderson wrote:
'Programming to an interface' does *not* refer to the syntactic construct
of an interface, but the semantic idea of a set of defined,
It does refer to the syntactic construct of an interface when it comes
to best practices in Java.
Many construe it to mean that, it's true.
public methods. What in Smalltalk would be called a 'protocol'. An
abstract base class can define an interface for this purpose just as well
as an interface (IYSWIM).
Arne Vajh?j wrote:
It can.
And it does for all the languages that does not have a special
syntax for interfaces.
But an explicit interface syntax makes it a bit more stringent,
because it is enforced that it does not carry any implementation.
The best practice in Java is to program to the interface according to Java's
definition of "interface". See Bloch, /Effective Java/, Item 18, "Prefer
interfaces to abstract classes".
Some of his points:
Existing classes can be easily retrofitted to implement a new interface.
Interfaces are ideal for defining mixins.
Interfaces allow the construction of nonhierarchical type frameworks.
Absolutely. So when you need to do any of those things, separate the
interface and the base class.
Interfaces enable safe, powerful functionality enhancements
What on earth does that mean?
He goes on in that chapter to recommend implementating an interface with
an abstract class to provide default method implementations, and to
publish the interface to client code, just as the OP did.
Another point on which i think Josh is talking sententious codswallop.
I'll add it to my list.
This reminds me of one of the problems that arises with design patterns.
When people first learn about them, it's very common for them to shoehorn
as many of them as they can into their code. But the thing about patterns
is that they aren't magical ingredients for making great code: they're
solutions to problems (or shapes of solutions to shapes of problems,
somewhat shadows-in-the-cave style), and if you don't have the problem,
applying the pattern doesn't solve anything, it just adds useless
verbiage. I think Josh Bloch (or perhaps his disciples) is making a
similar mistake. Yes, there are some practices which are always
appropriate, but there are some which are appropriate in certain
situations. This is the latter kind of practice, but the former kind of
situation.
tom
--
curry in a sack