Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 =;
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);, 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

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


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.