From ruby-talk Thu Sep 19 14:43:00 2002 From: "Jason Voegele" Date: Thu, 19 Sep 2002 14:43:00 +0000 To: ruby-talk Subject: Re: Is better to subclass or to add methods to an existing class? X-MARC-Message: https://marc.info/?l=ruby-talk&m=103244661605204 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%40posting.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