object.enable() anti-pattern

Roy Smith roy at panix.com
Wed May 8 09:17:17 EDT 2013


In article <518a123c$0$11094$c3e8da3 at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> 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:
> 
> 
> f = file("some_file.txt")
> f.open()
> data = f.read()

I've worked with C++ code that did this.  At one point in the evolution 
of OOP group consciousness, there was a feeling that constructors must 
never fail.  I don't remember if it was a general language-agnostic 
pattern, or a specific C++ reaction to poor exception handling code in 
early compilers.  What came out of that was the pattern you describe.  
All the code that could fail was factored out of the constructor into an 
"enable" method.

That being said, sometimes there are good reasons for doing this.  One 
example might be something like:

frobnicator = Frobnicator()
for file in my_file_list:
   frobnicator.munch(file)
   for line in frobnicator:
      process(line)

If creating a Frobnicator instance is very expensive, it might pay to 
create an instance once and keep reusing it on multiple files.  Here, 
munch() is your enable() method.  But, that's not quite what you were 
talking about.



More information about the Python-list mailing list