From: Robert Klemme Date: 2004-07-22T18:22:04+09:00 Subject: Re: Referencing objects and program design "Stephan K�mper" schrieb im Newsbeitrag news:2m86vsFj140oU1@uni-berlin.de... > Hi all, > > suppose I have some kind of object which holds 'object ids' referring to > other objects, probably objects of its own class - or even itself. > > Now adding an object to the list can be done (at least) in two ways: > Pass an object to the method and let the method find out the object id, > or pass the object id directly. If there are no special requirements for your object ids I suggest to use Object#id and ObjectSpace#_id2ref: 11:10:05 [ruby]: irb irb(main):001:0> class Foo;end => nil irb(main):002:0> f=Foo.new => # irb(main):005:0> id = f.id => 135020508 irb(main):006:0> ObjectSpace._id2ref id => # irb(main):007:0> > Now the following lines are just an example of what I'm thinking about > (and it's certainly not thread safe among other things). > > class Common_Base > @@curr_oid = "aa" I'd change that to be an instance var of Common_Base: @curr_oid = "aa" > attr_reader :oid > > def initialize > @oid = Common_Base.get_new_oid > end Note that, depending on whether you want to be able to resurrect instances from some kind of persistent storage, you may need to be able to override the oid. > def Common_Base.get_new_oid > @@curr_oid = @@curr_oid.succ > end > end > > class Reference_List < Common_Base > def initialize > super > @refs = [] > end > > def add_ref1( other ) > @refs << other.oid unless @refs.include? other.oid > end > > def add_ref2( oid ) > @refs << oid unless @refs.include? oid You could better use a Set here. That saves you the inefficient check (with an Array this is O(n) where n is the number of oids stored so far; with a Set (hash internally) it's ~ O(1)). > end > end > > class Referenced < Common_Base > end > > refl = Reference_List.new > ref = Referenced.new > > refl.add_ref1( ref ) > p refl # -> > > refl.add_ref2( ref.oid ) > p refl # -> > > refl.add_ref1( refl ) > p refl # -> > > > Now, for 'add_ref1' the method needs to know a bit more about the object > to be added (needs to call the oid method of the added method), while > 'add_ref2' seems to put more work on the caller of the method (needs to > ask for the added oid). > Anyway, right now using 'add_ref1' _seems_ to be more the > 'tell-the-other-guy' way, but I'm not too sure about that... > So, what's the better way to add a to-be-referenced object to the > referencing object? I'd go for add_ref1 - although you should uncover a bit more of the problem you are solving. Regards robert