On 10/7/16 3:12 PM, Stefan Zobel wrote:
... After having looked at lots of generic APIs, it seems to me that a
style has emerged where wildcards are used whenever possible, and type
parameters are used only when necessary, ...
Yes, I'm familiar with that kind of reasoning (I think Josh Bloch stated
that principle in "Effective Java"). But, to be honest, I never thought
that it should apply as a strict rule in all circumstances.
Yep, it's in Effective Java, near the end of Item 28:
“As a rule, if a type parameter appears only once in a method
declaration, replace it with a wildcard.”
Rhetorical question: do you really think that a signature employing 3
wildcards is easier to understand for the proverbial "average Joe" than
a bounded type parameter that expresses the sub-type relationship clearly?
I do not.
But anyway, you probably have to follow the established "style".
It's just too bad that most Java programmers I know won't understand the
proposed signature of 'flatMap'.
Turns out that Rémi's example exposes the difference between the wildcard
approach and the type-parameter approach. Returning to the example,
Optional<Integer> oi = Optional.empty();
Function<Number, Optional<StringBuilder>> fm = n -> Optional.empty();
Optional<CharSequence> ocs = oi.flatMap(fm);
If the flatMapper function itself has a wildcard type, for example,
Function<Number, Optional<? extends CharSequence>> fm = n ->
Optional.empty();
then this will still work with the wildcard approach but fail with the
type-parameter approach. As Rémi also pointed out, a wildcarded type can result
from the capture of a type with a wildcarded type parameter.
Based on this, I believe the nested wildcard approach to be the correct one.
s'marks