1

What is the general solutions to allow the client to choose the concrete instance of a method output?

For example, in the Lucene API the search method receives and modifies the collector input parameter, but this is generally regarded as a bad practice:

IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;

An alternative would be to provide a Factory as input and have the search method return the instance created.

What else?

1
  • ...receives and modifies the collector input parameter, but this is generally regarded as a bad practice - why so? Feb 26, 2013 at 15:17

1 Answer 1

5

Generics - quite obviously? In C# it might look like:

public class Searcher
{
    public IEnumerable<T> GetResults<T>()
    {
        return new[] { default(T) };
    }
}

And then:

var searcher = new Searcher();
IEnumerable<string> results = searcher.GetResults<string>();
1
  • Instantiating a generic type is not supported everywhere, namely Java. And even if it was, each subtype might have it's own constructor, and the Searcher should know nothing about that. Feb 26, 2013 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.