Alex Martelli wrote: >> What I think I'm trying to get at is that I believe that most >> situations where someone actually tries to do something in the base >> initialiser which requires calling a virtual method are probably also >> cases where the initialiser is doing too much: i.e. separating the >> construction/initialisation from actually doing something is usually >> a good idea. > > But why should that be? Template Method is perhaps the MOST generally > useful design pattern -- why would it be any less useful in > initialization than elsewhere?! > Because it is error prone?
Any method which is called from the constructor/initialiser has to operate correctly on an object which at that point is not fully constructed/initialised. So instead of having to write a method on a Foo object, your template method has to operate on a partial Foo. The danger is that you haven't clearly defined the partial Foo interface sufficiently and the method tries to use other parts of the object which haven't yet been set up. That situation gets worse when you have a class hierarchy as the subclass needs to know that it has to do complete its own initialisation before constructing the base class instead of afterwards, and if you are going to document that requirement, why not do it properly and split the construction in two? That's why I would go for the 2-phase construction: after the first phase you have an object which is fully initialised, just not yet used/connected/running. For example httplib.HTTPConnection does this: you construct the object with a host and port, but the actual connection is triggered by a separate object. I would suggest your example of a database connection belongs in that category: it should have an initial unconnected idle state and a separate connection. I think your example of a composite window building subwindows is the sort of use case I was asking for: it does sound tempting to construct the window and all its subwindows together. I'm happy to concede on that one. -- http://mail.python.org/mailman/listinfo/python-list