Default method survey results
Zhong Yu
zhong.j.yu at gmail.com
Fri Aug 17 10:27:03 PDT 2012
On Thu, Aug 16, 2012 at 12:32 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
>> 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.
That means it was a mistake to include remove() in Iterator. And now
we use a tool to mask that mistake, ending up with 2 mistakes. There
should not be a default impl of Iterator.remove() - a default impl
must work in all cases, not just in common cases.
Zhong Yu
> 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