Producing an abstract collection from an abstract collection

This issue has been bugging me for a while. Abstractly speaking, regardless of language, there are often situations when you want to have a method like this:

Collection method(Collection c) {
    // select some elements from c based on some filter 
    // and return a new collection
}

Now, Collection is in this case some abstract class (Like say IList in C# or List in Java) with several implementations. I've been wondering what exactly is the right procedure to produce the abstract collection?

Is it ok to create a concrete collection inside the method and return it? Like:

Collection method(Collection c) {
   Collection cc = new ConcreteCollection();
   // select some elements from c based on some filter 
   return cc;
}

This of course puts a constraint on the resulting collection and will produce problems in case, for some reason, we want to cast the result of the method to a different concrete collection than the one used inside the method.

Or, use reflection to determine the actual concrete type of c and create an instance of that class:

Collection method(Collection c) {
   Collection cc = c.getClass().newInstance();
   // select some elements from c based on some filter 
   return cc;
}

For some reason this does not seem very "elegant" to me. I would greatly appreciate some insight in this matter.

Answers


(Speaking for java). The reason you're returning Collection (an interface) rather than a concrete type (such as ArrayList) is that you're telling the user that they shouldn't care about what the actual concrete type being used is. This leaves you free to choose the appropriate type for your library/api.

If you're enforcing a particular concrete class, then you should be returning that concrete class, rather than the interface.

So, they shouldn't be casting your return type to anything else other than Collection. See When should I return the Interface and when the concrete class?.


Need Your Help

Can a Tap Gesture Recognizer in IB be used on a UILabel and/or UIImageView

iphone xcode uitapgesturerecognizer

I have an xib with a single UIView containing a bunch of images and labels. If I drag a Tap Gesture Recognizer onto the parent view, it works well, but I need to add code to determine the position ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.