From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2003-02-11T16:37:54+09:00 Subject: Re: inheriting from base classes In article , wrote: >Hi -- > >Gavin Sinclair and I have been involved in an interesting exchange >about the merits (or lack thereof) of inheriting from base classes, in >particular String/Array/Hash. This is also something that some of us >were chatting about at the conference in November. > >We're both very interested in hearing what people's views are on this. >Do you ever subclass String, Array, and Hash? Do you specifically >avoid doing so? > >A brief summary of some of what we've been saying follows: > >The argument in favor is that core classes already do a lot, and >specializing them can streamline things and economize on code. For >example: > > class ClassRoster < Array I'm more likely to think that ClassRoster 'has-a' Array then to think that ClassRoster 'is-a' Array. In this case I would use aggregation. > > class AssignmentValues < Hash Not quite sure from the name of the class, but I'll guess it has something to do with the previous context and assume that AssignmentValues might have something to do with the type of class you take in school... if so, then again, I don't see how it 'is-a' hash, but instead that it 'has-a' hash. Again, I'd use aggregation. > > class ExamQuestion::Title < String This one could go either way, I suppose, but again, I'd lean toward the 'has-a'. > >as opposed to: > > class ClassRoster > def initialize > @actual_roster = [] > end > end > I think this is fine- 'has-a' Array works here. >and so on. > >On the other hand, objects end up with more methods than will actually >be used. There's a kind of possible looseness to the fit. > >However... objects always at least potentially have "extra" >functionality in Ruby. Is there any reason not to rely on the >documentation of an interface? Don't we implicitly do that anyway >(since people can always add methods to objects and do unexpected >things, if that's what they're inclined to do)? > >There's also some question as to whether classes that inherit from >base classes should themselves be fairly generic, like > > class OrderedHash < Hash This seems to be a valid case for using inheritance: An OrderedHash 'is-a' kind of Hash. > >which also raises the question of where the boundary is between >generic and non-generic.... > >Thoughts? > In thinking back over the last couple of years that I've been using Ruby, the cases where I've subclassed builtins like Array, Hash or String have been very rare. I'm much more likely to favor aggregation ('has-a') over inheritance ('is-a') - as in the examples above. You can often use 'method_missing' to redirect method calls to the contained object. Also, if I need to add functionality to one of the built-in classes, I generally just add a method to the class instead of inheriting from it. That's kind of a controversial practice, though... Phil