Is better to subclass or to add methods to an existing class?

I think I’d only inject a method into an existing class if I need to modify
functionality of existing methods in code I couldn’t change. For example,
obviously many Ruby libraries using the String class. You can’t, at least
easily, modify all Ruby libraries to use a new subclass of String, but you
can cause them to behave differently when they invoke a standard String
method by redefining that method.

I’m sure some see that is a dangerous feature of Ruby, but it can be useful
in the right context.


On Thu, 19 Sep 2002, 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. For instance, if I
wanted to add a
rot13 method to the String class, all I have to do is this:

class String
> >   def rot13
> >     tr("A-Za-z", "N-ZA-Mn-za-m")
> >   end
> > end
> >
> > "foobar".rot13

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:

WARNING: All e-mail sent to and from this address will be received or
otherwise recorded by the A.G. Edwards corporate e-mail system and is
subject to archival, monitoring or review by, and/or disclosure to,
someone other than the recipient.