Re: Default Interfaces: possible Java extension?
On 2/11/2011 9:20 PM, Tom McGlynn wrote:
A commonly held principle for good programming is that we should
minimize dependencies on details of the implementation. One way to do
that in Java is with statements like:
List<String> names = new ArrayList<String>();
vs
ArrayList<String> names = new ArrayList<String>();
where the variable we use to hold the object has a type which only
allows (absent casts or reflection) use of the general contract for
List's without any visibility into the details of ArrayList's
implementation.
Here's a thought I've had for a small extension to Java that would
take this a little further. In the first example above, even though
we don't worry about the implementation after we get our list, we did
have to explicitly pick one kind of list. So...
Add a new optional element in the definition of an interface which
defines a class that does the default implementation of the
interface. E.g.,
interface List<T> default ArrayList<T> { ...}
An interface which has a default may be used in a constructor as:
List<String> name = new List<String>();
It seems to me that (in most cases, anyhow) an "interface with
a default implementation" is known as a "class." That is, with
DefaultList<String> name = new DefaultList<String>();
.... the thing on the right could be anything at all that extends
DefaultList. So, what have you gained? Maybe I'm missing something
(wouldn't be the first time), but I don't see the need.
It always seems a bit odd when I'm writing code when I have to import
ArrayList and use that class just the one time. It seems like code
could be a bit cleaner using this extension.
// Look, Ma, no one-shot imports!
List<String> name = new java.util.ArrayList<String>();
Are there other ways to do this? A factory method requires knowing
the class the factory resides in and I can't really think of other
patterns that address this. E.g., one could add
newSet(), newList() and newMap() methods to Collections but that's not
especially elegant to my eye since there's no special language
relation between the List interface and the Collections class.
I think that's the crux: There's no special relationship between
an interface and its many implementations; the relationship is one-way.
Adding the other-way relation -- the ability of an interface to name a
class and say "This is My beloved Son, in Whom I am well pleased" --
doesn't seem to me to add much utility.
Besides, a hundred forty-two experts would immediately blog about
why you should override the default. ;-)
--
Eric Sosman
esosman@ieee-dot-org.invalid