From: Eric Mahurin Date: 2008-02-24T08:27:02+09:00 Subject: Re: Monkeypatching is Destroying Ruby ------=_Part_4895_19945924.1203809229268 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Sat, Feb 23, 2008 at 4:36 PM, Avdi Grimm wrote: > On Sat, Feb 23, 2008 at 5:23 PM, Eric Mahurin > wrote: > > * adding new (or perceived missing) functionality (methods) to a class. > The > > traditional solution would be to just inherit from the class and use > the > > derived class instead where you want this new functionality. Since you > > can't inherit from some classes (i.e. immediates, a problem with the > > language IMHO), you can instead use something like Forwardable instead. > > Indeed. The irony here is that Ruby is perhaps the easiest language > in the world to implement delegation in. I'm planning on writing a > series of posts on alternatives to monkey patching, and delegation is > going to be one of the first techniques I talk about. > Here are the main alternatives I use (in order): * put the functionality elsewhere. The simplest example is instead of monkey-patching String#to_xyz, make XYZ::from_s. When your new class wants some interaction with a built-in class, put the functionality in the new class instead of monkey-patching it into built-in class. The monkey patching approach usually just saves you a few characters when using the new functionality. I do this 95% of the time where others might monkey-patch. * inherit the class where you want additional functionality and use the derived class instead. * use delegation if inheritance doesn't work (immediates). Delegation is basically just a "has-a" implementation of "is-a" (inheritance), but it gives a little more flexibility. I've never really had to use this when I was tempted to monkey-patch. It would be an interesting exercise to go through some of the ruby stdlib and show alternatives to monkey-patching. Eric ------=_Part_4895_19945924.1203809229268--