Default method survey results
Brian Goetz
brian.goetz at oracle.com
Thu Aug 16 10:32:44 PDT 2012
> The oddity of "default" implementation is that it puts the programmer
> in a box. He has to provide some sort of implementation that does not
> rely on state. That's an odd place to be in -- especially if no
> suitable implementation can be given without state.
No, there are plenty of default methods that can be implemented without
access to state. For example, there are optional methods. For example,
Iterator.remove() can have a default to throw UOE, so that the 99% of
Iterator implementations that don't want to implement remove() don't
have to implement a version that throws.
Another big category is methods that can be default-implemented in terms
of other methods, such as in the following:
public interface Traversable<T> extends Iterable<T> {
public void forEach(Sink<? super T> sink) default {
for (T t : this)
sink.accept(t);
}
}
Here, there's an obvious default implementation, which is good enough
for a lot of cases, but subclasses are free to provide a better one (for
example, ArrayList can provide an Iterator-less one.)
A third category is providing views. For example:
public interface Collection<E> {
Collection<E> asSynchronized() default {
return Collections.synchronizedCollection(this);
}
}
(with appropriate covariant overrides in distinguished subtypes of
Collection.)
Etc. Etc.
> Why not get rid of default implementations all together? Allow
> interfaces to be extended at will and the JVM simply throws a
> NotImplementedException (ala C# or Apache Commons Lang) if there is no
> overriding implementation.
Pushing the problem to runtime is not a good solution; a program that
compiles should not throw linkage errors.
C# extension methods are static, not virtual. While this makes them
simpler in some ways, it also makes them worse in a lot of ways too.
The primary motivation for adding this feature is to provide a path to
interface evolution, allowing interfaces like Collection to grow, in a
controlled manner, over time.
More information about the lambda-dev
mailing list