From: Robert Klemme Date: 2008-05-24T21:59:51+09:00 Subject: Re: How to model something Some random thougths... On 24.05.2008 13:08, Tobias Weber wrote: > my programm needs to store persons. They have a weight and a gender. You > are only allowed to ask males for their weight, females will throw > dishes/exceptions. There *is* a method to change someones gender. > > I could have 'if gender' in every accessor or use the state pattern. But > that has no state, so I'm confused. I would have to access the variable > in the wrapper class. I am not sure what you mean here. Here's one way to do it: class Person GENDERS = { :male => Class.new do def gender; :male; end def weight_check; end end.new, :female => Class.new do def gender; :female; end def weight_check; raise "Go away!" end end.new, }.freeze def initialize(gender) self.gender = gender end def gender=(g) @gender = GENDERS[g] or raise "Illegal gender #{g.inspect}" end def gender; @gender.gender; end def weight=(w) raise IllegalArgumentException, "negative" if w < 0 @weight = w end def weight; @gender.weight_check; @weight; end end > The programm can also shoot people into space, in which case the > implementation of weight changes but the same restrictions apply. > The proxy pattern will help here, probably by having weight first call > delegate.weight, and if that isn't NoMethodException multiplying with > gravity. Well, in that case #weight isn't just a simple accessor but it needs an argument (gravity). You probably want to have an attribute "mass" which stores the proper value. > Any advice or implementations of similar problems I could look at? > > (and in reality people are TV series with 6 genders and 5 other > attributes, and space is just but a remote place to store things) What are the other four genders? :-)) Kind regards robert