From: Josh Cheek Date: 2010-06-20T01:30:17+09:00 Subject: Re: General Ruby OOP question --0016e6db2ad4e5a73c04896495df Content-Type: text/plain; charset=ISO-8859-1 On Sat, Jun 19, 2010 at 8:56 AM, Paul A. wrote: > Hello, > > I have a general question about OOP with Ruby. If I have 2 class: Home > and Person for instance, such as: > > >> class Home > >> def initialize > >> @person1 = Person.new > >> @person2 = Person.new > >> # ... > >> end > >> > >> def open_a_window; end > >> # ... > >> end > > >> class Person > >> def play_wii_game; end > >> end > > Then, a home instance can include a lot of people. And that's cool. And > a home instance can apply action on a person using a method just like: > @person2.play_wii_game > > But if a person want to open a window in its home? Here, with a such > design it's impossible, isn't it. > > So to allow this kind of action, I think we need to pass as parameter > self inside Home initialization process, becoming: > > >> class Home > >> def initialize > >> @person1 = Person.new(self) > >> @person2 = Person.new(self) > >> # ... > >> end > >> > >> def open_a_window; end > >> # ... > >> end > > >> class Person > >> def initialize(home) > >> @home = home > >> end > >> > >> def open_a_window > >> @home.open_a_window > >> end > >> > >> def play_wii_game; end > >> end > > Now, a instantiated person can do it using open_a_window proxy method. > And any other proxifyable home's methods. > > But is it ethics? I mean, is that lawful under the principles of > object-oriented programming. Maybe this is so much power, to pass self > inside person instance inside its home... 'cause it's almost as if there > was no class, no partitioning. > > What do you think about this? > Thanks for any considerations. > -- > Posted via http://www.ruby-forum.com/. > > Plus, you get a nice little benefit in that the Person#open_a_window method can contain the conditionals for dealing with the edge case of when there is no home. class Person def open_a_window @home.open_a_window if @home end def has_home? !!@home end end Then later you can say things like person.open_a_window if person.hot? rather than having to cart the exception logic all over your implementaion person.open_a_window if person.hot? && person.has_home? Though, I suppose, it is a rather limited model in that your person may be at work, or at a friend's home. --0016e6db2ad4e5a73c04896495df--