Re: calling own methods from constructor
Tom Anderson <twic@urchin.earth.li> wrote:
On Wed, 6 Apr 2011, Andreas Leitgeb wrote:
Is there any *good* use of having the constructor call a method that
actually *can* be overridden in a subclass? I mean, are there
(non-anti)patterns of explicitly allowing subclasses to hook into
base-class's construction?
public abstract class Library {
private List<Document> documents;
protected Library() {
documents = new ArrayList<Document>();
Collection<String> titles = listDocuments();
for (String title: titles) {
Document doc = loadDocument(title);
// do other preparatory stuff with the document
documents.add(doc);
}
}
protected abstract Collection<String> listDocuments();
protected abstract Document loadDocument(String title);
}
public class FilesystemLibrary extends Library {
// ...
}
[...]
Sorry, in my eyes, this is one of the anti-patterns.
What are the alternatives?
It's hard to speculate about alternatives for an artificial example.
I'd say, that they exist for any reasonable specification of the problem,
and "back it up"(*) by declaring specifications for which no (or only
mindboggingly contrived) alternatives exist as unreasonable ;-)
(*): In German, we use double-quotes also to indicate tongue-in-cheek
formulations that aren't to be taken entirely literally/serious.
I've recently learned that they are not always thusly understood,
elsewhere. Therefore this explanation. Is there any common markup
for it that would be recognized in the English-speaking world?