object.enable() anti-pattern

Wayne Werner wayne at waynewerner.com
Thu May 9 07:08:25 EDT 2013



On Wed, 8 May 2013, Steven D'Aprano wrote:

> I'm looking for some help in finding a term, it's not Python-specific but
> does apply to some Python code.
>
> This is an anti-pattern to avoid. The idea is that creating a resource
> ought to be the same as "turning it on", or enabling it, or similar. For
> example, we don't do this in Python:

I'm not entirely sure what the name of it is, but the basic concept is 
that you should never partially create, or create a class that can be in 
an unstable state. Which isn't to say you should prevent invalid input, 
only that with every valid input or single operation (including 
construction) your class should be valid.


Ah, that's it - the problem is that it introduces /Temporal Coupling/ to 
one's code: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling/

You don't ever want a class that has functions that need to be called in a 
certain order to *not* crash. That's fine if you have to call them in a 
certain sequence in order to get the correct data - that's what 
programming is all about, after all. But if you provide me a class with a 
constructor you better make sure that when I do this:

     thing = YourSuperAwesomeClass()
     thing.do_stuff()

that I don't get some horrid stack trace ending with

     InvalidStateError: initialize() needs to be called before do_stuff()

Or something worse.


HTH,
Wayne

p.s. I'm interested in reading whatever is evenually written on the topic



More information about the Python-list mailing list