[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:       Jim Freeze <jim () freeze ! org>
Date:       2002-09-19 12:39:59
[Download RAW message or body]

On Thu, Sep 19, 2002 at 09:20:13PM +0900, 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:
> 
> [code]
> class String
>   def rot13
>     tr("A-Za-z", "N-ZA-Mn-za-m")
>   end
> end
> 
> "foobar".rot13
> [/code]
> 
> 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:
> 
> [code]
> class myStr(str):
>   def rot13(self):
>       trans = maketrans(
>                   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
>                   "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")
>       newstring = translate(word, trans)
>       return newstring
> 
> myStr("foobar").rot13()
> [/code]
> 
> or in Ruby
> [code]
> class MyStr < String
>   def rot13
>     tr("A-Za-z", "N-ZA-Mn-za-m")
>   end
> end
> 
> MyStr.new("foobar").rot13
> [/code]
> 
> 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.
> 
> Can you enligthen me and tell me if it's really that bad an idea to add
> methods to an existing class, or if he's just being a Python zealot?
> 

I can't speak of it being a bad idea, but a related feature of Ruby that
may be even more important than extending classes is extending objects.
(I don't know, can Python even dream of doing this?)

irb(main):001:0> s = "fred"
"fred"
irb(main):002:0> module Fred
irb(main):003:1> def rot13
irb(main):004:2> tr("A-Za-z","N-ZA-Mn-za-m")
irb(main):005:2> end
irb(main):006:1> end
nil
irb(main):007:0> s.extend Fred
"fred"
irb(main):008:0> s.rot13
"serq"

In this case I don't pollute the class and I don't have to 
make the expense of subclassing a big class like String.

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

Jim

-- 
Jim Freeze
----------
Programming Ruby 
 def initialize; fun; end
A language with class
[prev in list] [next in list] [prev in thread] [next in thread] 

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