object.enable() anti-pattern

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu May 9 22:30:21 EDT 2013


On Thu, 09 May 2013 19:34:25 +0100, MRAB wrote:

>> There is no sensible use-case for creating a file OBJECT unless it
>> initially wraps an open file pointer.
>>
> You might want to do this:
> 
> f = File(path)
> if f.exists():
>      ...
> 
> This would be an alternative to:
> 
> if os.path.exists(path):
>      ...

Sure, but your made-up File object does not represent a file, it 
represents a pathname which *may or may not* exist. Pathnames are not 
files. Not all files have a pathname that refers to them, and not all 
pathnames point to an actual file. Since it has an exists() method that 
can return False, there are so-called "File" objects that aren't files 
and the name is a misnomer. A much better name for the class would be 
"Path", not "File".

I'm not saying that there is never a use-case for some objects to have an 
"enable" or "start" or "open" method. That would clearly be a silly thing 
to say. In the real world, we design many objects to have a start switch. 
It would be pretty horrible if your car was running all the time. But 
that's because there are actual use-cases for having cars *not* run, and 
"make it stop" is the safe default behaviour.

Your fridge, on the other hand, doesn't have a "make it go" button. So 
long as power is applied to it, your fridge automatically runs. Likewise, 
your watch is an "always on" device, provided it hasn't wound down or 
have a flat battery. Your fire alarm is "always on". 

I must admit I am astonished at how controversial the opinion "if your 
object is useless until you call 'start', you should automatically call 
'start' when the object is created" has turned out to be.



-- 
Steven



More information about the Python-list mailing list