From: stefano Date: 2003-05-12T22:22:13+09:00 Subject: Re: [OO interface design] Pass-by reference VS encapsulation ? On Wed, 30 Apr 2003 21:17:23 +0000, Simon Vandemoortele wrote: >> a) contacts can be aware that they are 'contained' (in an address book) >> b) contact methods use this awareness when ri can be violated > Yes, that is what I meant by a solution where 'the contacts cooperate > with the addressbook'. > I don't know ... but I do feel the potential for re-using the Contact > class outside the Addressbook is rather limited anyway so I wouldn't > feel too bad about coupling them. Well, you could have a base class "Contact" and a derived class "BoundContact" (sorry, can't think of a better name :-) silly example: --CUT-- class Contact def initialize(someValues) @name = someValues['name'] ... end def setName(aName) @name = aName end def to_h { 'name' => @name ... } end def putInAddressBook(aBook) return BoundContact.new(aBook, to_h) end end class BoundContact < Contact def initialize(anAddressBook, someValues) @addressBook = anAddressBook super end def setName(aName) unless @addressBook.findContact(aName) super else raise "Contact '#{aName}' already exists" end end def getUnboundContact return Contact.new(to_h) end end --CUT-- silly example, using encapsulation: --CUT-- class Contact def initialize(someValues) @name = someValues['name'] ... end def setName(aName) @name = aName end def to_h { 'name' => @name ... } end def putInAddressBook(aBook) return BoundContact.new(aBook, self) end end class BoundContact def initialize(anAddressBook, aContact) @addressBook = anAddressBook @contact = aContact end def setName(aName) unless @addressBook.findContact(aName) @contact.setName(aName) else raise "Contact '#{aName}' already exists" end end def getUnboundContact return @contact end end --CUT-- -- "Any time you've got both the pope and the Dixie Chicks against you, you're not long for the White House" -- Michael Moore