Problem of defender methods with generic methods

Steven Simpson ss at comp.lancs.ac.uk
Mon Nov 15 16:32:12 PST 2010


Hi Alex,

On 15/11/10 22:30, Alex Buckley wrote:
> Hi Steven,
>
> On 11/15/2010 5:46 AM, Steven Simpson wrote:
>> It's more plausible, then, that the API writer would use one of the
>> following options:
>>
>>    1. Just use List<? extends Comparable> in the interface, with
>>       Collections.max(..) in the implementation.
>>    2. As above, but with static extension methods (but still no dynamic
>>       dispatch on the max call itself).
>>    3. Add a List defender that imposes additional constraints on <T>, as
>>       Ali Ebrahimi seems to have tried to do.
>
> Just to clarify, for (2), do you mean adding an extension method to
> interface List<T>:
>
> public interface List<T> {
>   <A extends Comparable<? super A>>
>   extension A max()
>   default Collections.<A>max;
> }

No, I'm simply talking about the static alternative to extension
methods, as C# has (AIUI), which are just syntactic sugar for a static
method call.  The problem shouldn't arise there, as the existence of an
extension method like max() doesn't require that all Lists have its
additional <? extends Comparable> constraint.  (1) and (2) are
semantically equivalent.

> (By "no dynamic dispatch on the max call", I presume you mean a
> scenario where there is no CustomizedList<T> to override List<T>'s max.)

No, following on from above.  With a static extension method, not a
dynamic defender method, List implementations aren't able to override
the default, because it's just a static call.  I'm merely acknowledging
that static extensions have their own problems.

> And furthermore not introducing CustomizedList<T>?

Yes, all three options are intended to avoid having two interface types,
e.g. Base<T> and Derived<T extends Comparable>, just because one of the
extension methods has the extra constraint.  Option 4 is to introduce a
new type.  ;-)

(I've slightly transposed Ali's problem by imagining that he'd prefer to
add these extensions directly to List, and that he's only introduced
CustomizedList for the sake of toying with the new language features.  I
don't think that fundamentally alters the problem though, which is that
two of his extensions work best with List<T>, while the other one
demands List<T extends Comparable>.)

Cheers!


More information about the lambda-dev mailing list