James Gray
1/17/2008 9:10:00 PM
On Jan 17, 2008, at 3:02 PM, Rick DeNatale wrote:
> On 1/17/08, James Gray <james@grayproductions.net> wrote:
>> On Jan 17, 2008, at 1:04 PM, J. Cooper wrote:
>>
>>> 1. Open classes. The other day, in a little Blackjack game I wrote
>>> in
>>> Ruby, I used this feature to add in a method to the Array class
>>> instead
>>> of making a class that inherited from Array and added that method.
>>> However, a) I'm not sure if that was the "right" way and b) I'm not
>>> sure
>>> if there is an advantage to that approach over the latter, per se.
>>
>> Open classes are best used sparingly. There are problems with them,
>> of course, in that your code might collide with someone else's code.
>> The plus though is that all instances of the changed class are
>> suddenly empowered with new methods you can count on. Some good
>> uses,
>> in my opinion, are:
>>
>> * Conversion methods
>> * DSL
>
> I think that rather than sparingly, the adverb should be carefully.
>
> Open classes are very powerful in situations like building a
> framework, (e.g. Rails). Features such as plugins, use formalized
> patterns of extending open classes to allow opening classes while
> minimizing the potential for collisions.
In an example in Practical Ruby Projects, the author has to load some
some operating specific code. He feels that open classes are great
for that. He codes up the general interface of the class and then
insert the other methods tailored to the operating system later.
This does seem to come out smoother than having to deal with a bunch
of specific subclasses. The unneeded code is just not added in.
James Edward Gray II