From: sur max Date: 2007-02-16T22:09:04+09:00 Subject: Re: class design issues ------=_Part_2990_7455128.1171631339369 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline I think just declaring it as attr_accessor is not that much a protection !! its fine that lf1.name # => error, undefined method `name=' f BUT, it can easily be broken as.... lf1.instance_variable_set("@name", "new broken name") lf1.name # => "new broken name" 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 > 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 > > -- sur http://expressica.com ------=_Part_2990_7455128.1171631339369--