Generic wildcard types should not be used in return parameters

The main benefit of using wildcard types, say in method formal parameter, is to provide flexibility to the user to pass, say any type of Collection, or List or anything that implements Collection (assuming that the collection is declared like Collection<?>). You would often find yourself using wildcard types in formal parameters.

But ideally you should avoid using them as return type of your method. Because that way, you would force the user of that method to use wildcard types at the caller end, even if they didn’t want to. By using wildcard types, you’re saying that, hey! this method can return any type of Collection, so it’s your job to take care of that. You shouldn’t do that. Better to use bounded type parameter. With bounded type parameter, the type will be inferred based on the type you pass, or the target type of the method invocation.

And here’s a quote from Effective Java Item 28:

Do not use wildcard types as return types. Rather than providing
additional flexibility for your users, it would force them to use
wildcard types in client code.
Properly used, wildcard types are
nearly invisible to users of a class. They cause methods to accept the
parameters they should accept and reject those they should reject. If
the user of a class has to think about wildcard types, there is
probably something wrong with the class’s API.

Leave a Comment