I tend to only return a List or Set if it is really important that the return value actually is a List or Set. That way, if I want to change from a List to a Set or vice versa, or return the values() collection of a map, it's easier to change.
However, it is easier for calling code if you return List, and the following example shows exactly why:
So you'll have to make a decision: either make it easier for you to return something else, or make it easier for users of your method. But users of your method can easily convert like my example code if really necessary.
I also agree with Bear: always define the return type (and parameter types and (instance) variables as well) as interfaces, never as implementing classes.
That is, again, unless you really need something specific from an implementing class. If you need something that's both a List and Queue, you can declare as List, use a LinkedList and cast to queue (or vice versa), or store two references to the same LinkedList object. But in that case, I think declaring as LinkedList is justified.
Bear Bibeault wrote:It's sort of like asking "Give me a 3/4-inch wrench" vs. "Give me a 3/4-inch Craftsman wrench". What? A Husky or Stanley wrench won't do?
Well, I've got some Snap-on wrenches that will fit places where a Craftsman won't. But the concept is the same, most of the time, all you want is a 3/8-inch wrench. If you care, you can say box end, open end, etc. In the real world, you never use an adjustable wrench when you can use a fixed on, and when you need a deep well socket, say so. Never, ever use pliers on a nut. I guess that would be similar to returning a Collection. Even a Collection<EmailAddress> is better than just a Collection
I too use the most general type that will work. In this case that would be List or Collection depending on what I plan to do with the result. Is it supposed to be ordered?
The reason I do this is that things might change in the future and I might want a different subtype. This happened with Vector ---> ArrayList. What happens if someone creates a more efficient list in the future? Doesn't seem likely. But then, I imagine people didn't think Vector would become "un-recommended" either.
I don't think I've ever used Collection as a return type. Most of the time, I either want ordering and/or direct access -in which case List is called for- or the Set quality of no duplicates. Not caring about either is extremely rare.
But I also have a hard time picturing a situation where today I'd want to use a List, and maybe later might want to switch to a Set. Not to say it couldn't ever happen, but it seems very unlikely. So the genericity of using Collection seems overkill.