J
james.d.masters
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
Thanks in advance,
-James
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
Thanks in advance,
-James