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
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