Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
...receives and modifies the collector input parameter, but this is generally regarded as a bad practice - why so? –  Konrad Morawski Feb 26 '13 at 15:17

1 Answer 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>();
share|improve this answer
    
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. –  Miguel Fonseca Feb 26 '13 at 17:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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