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

I say FOO-ey on your friend. :slight_smile: Tacking on a new method is muy cool and
muy agile. I would only worry about putting some hard constraints on this
idiom if you see this new tool used over and over again. Then maybe
formalize it in it鈥檚 own class, sub-class, or mixin. Working hard on a
problem before it requires hard work is anti-efficiency and anti-fun (well,
in my definition of fun).

Drew

路路路

-----Original Message-----
From: Vincent Foley [mailto:vinfoley@iquebec.com]
Sent: Thursday, September 19, 2002 8:20 AM
To: ruby-talk@ruby-lang.org
Subject: Is better to subclass or to add methods to an existing class?

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鈥檛 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:

class myStr(str):
  def rot13(self):
      trans = maketrans(
                  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
                  "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")
      newstring = translate(word, trans)
      return newstring

myStr("foobar").rot13()

or in Ruby

class MyStr < String
  def rot13
    tr("A-Za-z", "N-ZA-Mn-za-m")
  end
end

MyStr.new("foobar").rot13

His main argument was just that, 鈥淚t鈥檚 the Wrong Way 鈩 to do it鈥. To me,
it just seems like extra code and added complexity.

Can you enligthen me and tell me if it鈥檚 really that bad an idea to add
methods to an existing class, or if he鈥檚 just being a Python zealot?

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

Cheers,

Vince

Vincent Foley-Bourgon
Email: vinfoley@iquebec.com
Homepage: http://darkhost.mine.nu:81