From: Robert Klemme Date: 2005-01-05T01:11:39+09:00 Subject: Re: Composition or Module "Tomoyuki Kosimizu" schrieb im Newsbeitrag news:20050104.233447.97297001.greentea@fa2.so-net.ne.jp... > Hi, > > Let me hear your opinions, composition or module. > > Composition: > > class Representation > def to_string(obj) > return sprintf('%s=%s', obj.class, obj.value) > end > end > > class Domain > def initialize > @value = 10 > end > attr_reader :value > > def to_s > Representation.new.to_string(self) Not efficient because you create a stateless instance every time you need the conversion to string. You could make Representation a singleton though. > end > end > > puts(Domain.new) > > or Module: > > module Representation > def to_s > return sprintf('%s=%s', self.class, @value) Rather do this as it is more flexible: return sprintf('%s=%s', self.class, self.value) Also, you might want to add def value() nil end to avoid errors for classes that don't implement "value()". > end > end > > class Domain > include Representation > > def initialize > @value = 10 > end > end > > puts(Domain.new) Why do you want to separate this if you override Domain#to_s (i.e. a standard method) anyway? You could as well - put the implementation into Domain#to_s and leave out Representation - Make the conversion an instance method of the module so you don't need to create new instances of the module all the time (for composition). - Take the second approach (i.e. the one with the mixin) but make Representation a base class. Maybe there are other options but that depends on your design goal. If you tell a bit more maybe we can come up with a more appropriate solution. Kind regards robert