From: Trans Date: 2007-03-15T16:11:32+09:00 Subject: Re: General Ruby OOP Question - using inheritance or include for shared attributes On Mar 15, 1:35 am, james.d.mast...@gmail.com wrote: > I have a generic Ruby OOP question. Which is the more "correct" way > to share methods between two similar classes that do not necessarily > need to inherit from anything else: inheritance or include (as a mix- > in)? I realize that this question may be subject to opinion; however, > I'm getting ready to formally release a library and I'd like to do the > "right" thing. I like the inheritance route but I'm not sure that > creating a "Base" class that will never be instantiated directly by > anything externally is "proper". > > Here are examples of both approaches: > > ### EXAMPLE 1 (inheritance): > > # Here Base.new will (should) never be called directly; only through > inheriting classes > class Base > def initialize() > @records = {} > end > > def get_record(key) ; @records[key] ; end > > def set_record(key, value) ; @records[key] = value ; end > end > > class RecType1 < Base ; end > class RecType2 < Base ; end > > ### EXAMPLE 2 (mix-in): > > module Base > def init_record() > @records = {} > end > > def get_record(key) ; @records[key] ; end > > def set_record(key, value) ; @records[key] = value ; end > end > > class RecType1 > include Base > def initialize() > init_record > end > end > > class RecType2 > include Base > def initialize() > init_record > end > end When it comes to Ruby there is a huge consideration here: Do you or will you ever wish to pass on class level methods? Or more technically speaking, do you want class singleton methods to be in the inheritance chain? If so then you have to use a class, since modules don't allow it (to my eternal dismay). For example: class X; def self.x; "x"; end; end class Y < X; end Y.x #=> x module X; def self.x; "x"; end; end class Y; include X; end Y.x #=> error IMHO It's unfortunate that this is the case --or at least that there's not a method other than #include that can do it. I guess it's because I wrote annotations, which turned out to be very tricky b/c of this. T.