Bounded wildcards are contagious, which is what the page you link to seems to lament. Well, there's no denying that... but I guess I don't see it as such a big problem.
There are many cases where I return a bounded wildcard exactly because it's contagious. The JDK, for better or worse (I say for worse, but that's a different soap box :) ) doesn't have interfaces for read-only collections. If I return a List<Foo>
that I don't want people modifying (maybe it's even safely wrapped in Collections.unmodifiableList
), there's no way to declare that in my return signature. As a poor-man's workaround, I'll often return List<? extends Foo>
. It's still possible to try to modify that list by removing elements or inserting null
, but at least the fact that you can't add(new Foo())
serves as a bit of a reminder that this list is probably read-only.
More generally, I think returning something with a bounded return type is perfectly reasonable if you really want the call site to have restricted access to the object.
Another example would be a thread-safe queue that you hand off to different threads, where one thread is a producer and the other is a consumer. If you give the producer a Queue<? super Foo>
, it's clear that you intend them to put items into it (and not take items out). Likewise, if you give the consumer a Queue<? extends Foo>
, it's clear you intend them to take items out (and not put items in).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…