From: Robert Dober Date: 2007-02-16T22:08:42+09:00 Subject: Re: class design issues On 2/16/07, Robert Klemme wrote: > On 16.02.2007 13:51, Spitfire wrote: > > I have a class which takes an input and produces an object. Let's say, > > it takes inputs about specifications of a life-form, and then creates it > > (instantiates say an object, 'LifeForm'). Let's call this factory class > > 'Creator'. Now, my problem is how do I ensure that once 'Creator' > > returns a 'LifeForm', any external/requestor class can only view the > > properties of LifeForm, that were set during creation, and not be able > > to modify them??? > > How do I design these imaginary classes 'Creator' and 'LifeForm'? > > First, it is very hard to actually prevent changes of instance variables > (if it is possible at all). For your purposes it is probably sufficient > to define attribute readers only. Second, you do not necessarily need a > second class - basically LifeForm is the factory for LifeForm instances. > So you could do > > class LifeForm > attr_reader :age, :name, :foo > > def initialize(age,name,foo) > @age = age > @name = name > @foo = foo freeze and you might add freeze here, now it becomes quite tough to change the LifeForm object. Personally I do not know any way to modify it now, but someone will show us soon, I am quite sure ;) HTH Robert > end > end > > irb(main):010:0> lf1 = LifeForm.new 10, "bla", "buzz" > => # > irb(main):011:0> lf1.name > => "bla" > irb(main):012:0> lf1.name = "ddd" > NoMethodError: undefined method `name=' for # @name="bla", @foo="buzz", @age=10> > from (irb):12 > from :0 > > HTH > > robert > > -- We have not succeeded in answering all of our questions. In fact, in some ways, we are more confused than ever. But we feel we are confused on a higher level and about more important things. -Anonymous