object.enable() anti-pattern

Roy Smith roy at panix.com
Fri May 10 10:01:14 EDT 2013


In article <mailman.1527.1368188358.3114.python-list at python.org>,
 Robert Kern <robert.kern at gmail.com> wrote:

> I'd be curious to see in-the-wild instances of the anti-pattern that 
> you are talking about, then. I think everyone agrees that entirely 
> unmotivated "enable" methods should be avoided, but I have my doubts 
> that they come up very often. 

As I mentioned earlier in this thread, this was a common pattern in the 
early days of C++, when exceptions were a new concept and handled poorly 
by many compilers (and, for that matter, programmers).

There was a school of thought that constructors should never be able to 
fail (because the only way for a constructor to fail is to throw an 
exception).  The pattern was to always have the constructor succeed, and 
then either have a way to check to see if the newly-constructed object 
was valid, or have a separate post-construction initialization step 
which could fail.

See, for example, the isValid() and Exists() calls for RogueWave's 
RWFile class (http://tinyurl.com/c8kv26g).  And also, 
http://tinyurl.com/cgs6clx.

Even today, there are C++ implementations which do not use exceptions.  
Some are for use in embedded or real-time systems where things need to 
be strictly time-bound and/or memory-bound.  Others are for historical 
reasons (http://tinyurl.com/6hn4zo).

Once people were used to writing "can't fail" constructors in C++, they 
often continued using that pattern in other languages, where the 
underlying reasons no longer made sense.  Quite possibly, they never 
even knew the underlying reasons; they were taught, "Constructors must 
never fail", and assumed it was a universal rule.

This, BTW, is one of my biggest beefs with the classic Gang Of Four 
pattern book.  It presents a bunch of patterns as being universally 
applicable, when in reality many (if not most) of them are highly C++ 
specific.

BTW, whenever I read things like, "I think everyone agrees", I 
automatically assume what the writer really meant was, "I, and all the 
people who agree with me, think".



More information about the Python-list mailing list