object.enable() anti-pattern

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed May 8 04:52:12 EDT 2013


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:


f = file("some_file.txt")
f.open()
data = f.read()


because reading the file can fail if you forget to call open first. 
Instead, Python uses a factory function that creates the file object and 
opens it:

f = open("some_file.txt")  # if this succeeds, f is ready to use
data = f.read()


Basically, any time you have two steps required for using an object, e.g. 
like this:

obj = someobject(arg1, arg2)
obj.enable()

you should move the make-it-work functionality out of the enable method 
and into __init__ so that creating the object creates it in a state ready 
to work.

I read a blog some time ago (a year ago?) that discusses this anti-
pattern, and I'm pretty sure gave it a specific name, but I cannot find 
it again. Can anyone find any references to this anti-pattern? My google-
fu is letting me down.



(For what it's worth, I'm refactoring some of my own code that falls into 
this anti-pattern. Die, enable method, die die die!)


-- 
Steven



More information about the Python-list mailing list