OOP / language design question

bruno at modulix onurb at xiludom.gro
Wed Apr 26 05:36:26 EDT 2006


Duncan Booth wrote:
> 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?

Programming *is* error prone.

> Any method which is called from the constructor/initialiser has to operate 
> correctly

any method has to operate correctly anyway !-)

>  on an object which at that point is not fully 
> constructed/initialised.

In Python, when the __init__ method is called, the object is at least
fully constructed.

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

If so, the worse thing that can happen is an exception - and you'll
surely spot the problem really soon.

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

It's *already* split : __new__ construct the object, __init__ initialize it.

> That's why I would go for the 2-phase construction:

But that's already what you have.

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

If you look at file objects, they do try and open the file at init time.
Is a net or db connection that different ?

(snip)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list