[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Is better to subclass or to add methods to an existing class?
From:       "Jason Voegele" <jason () jvoegele ! com>
Date:       2002-09-19 14:43:00
[Download RAW message or body]

Vincent Foley wrote:
> I was discussing with a (Python) friend last night.  I told him that one
> thing I liked better about Ruby than Python was that you could add
> methods to already existing methods.
[snipped example]
> But my friend told me that Python didn't have that because it was not a
> good thing and it was not the proper way to do it.  He said that the
> true way of doing it, is to subclass (since Python 2.2 can now subclass
> builtin types) the base class
[snipped another example]
> His main argument was just that, "It's the Wrong Way (TM) to do it".  To
> me, it just seems like extra code and added complexity.

First, note that the subclassing technique will not work if you do not
create the objects yourself (i.e. they are created by another part of the
system and you cannot control how they are created.)  You could use a
"copy constructor" technique in your subclass to get around this, but it's
often more trouble than it's worth and also less efficient.

That said, it's true that most of the time subclassing is a better idea
because adding methods to an existing class can sometimes lead to name
clashes.  Even then, though, you might be better off by dynamically adding
a singleton method to an individual object, rather than an entire class:

my_string = get_my_string_from_somewhere()
def my_string.rot13
    tr("A-Za-z", "N-ZA-Mn-za-m")
end

This way your string has rot13 capabilities but other strings will not be
affected by this.

I posted some arguments in favor of the Ruby approach to comp.lang.python
a while back.  The post can be found at:

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=91acf731.0112050832.947307f%40 \
posting.google.com&prev=/groups%3Fq%3Dvoegele%2Bruby%2Bmethod%2Bgroup:comp.lang.python \
.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D91acf731.0112050832.947307f%2540posting.google.com%26rnum%3D2


(If that URL doesn't work for you due to wrapping, you can search for the
thread "Python evangelists unite!" on comp.lang.python).

> I'd also like to know if other OO languages (SmallTalk, Eiffel, Sather,
> etc.) allow class modifications.

Smalltalk allows class modifications, Eiffel does not, I don't know about
Sather.

-- 
Jason Voegele
"We believe that we invent symbols. The truth is that they invent us."
    -- Gene Wolfe, The Book of the New Sun


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic