From: Paul Lutus Date: 2006-09-21T05:55:12+09:00 Subject: Re: Message passing between objects Tod wrote: / ... > To me that looks like two objects communicating directly with one > another. It is, and IMHO it should be avoided to the degree possible. Again IMHO, the best data structure is a pure object-oriented one, in which all the data objects are related by a class hierarchy, rather than by ad hoc message-passing. In the above example, the "registrar" class would possess the data available for each student and allow by direct access what would otherwise require a message protocol. Example: ------------------------------------- #!/usr/bin/ruby -w class Registrar Names = [ "Tom","Dick","Harry","Moe","Larry","Curly" ] Classes = [ { :name => "Home economics", :gpa => 2.0 }, { :name => "Post-modernism", :gpa => 1.5 }, { :name => "Literature", :gpa => 3.2 }, { :name => "Comparative blogging", :gpa => 3.0 }, { :name => "Quantum physics", :gpa => 3.5 } ] def initialize @student_list = [] 1000.times do |n| @student_list << Student.new(n,Names[n % Names.size],2.0 + rand(100) / 50.0) end end def get_student_data(n) return @student_list[n] end def handle_application(student,class_data) if student.gpa < class_data[:gpa] puts "\tNo, forget it, #{student.name}, you aren't smart enough for the #{class_data[:name]} class." else student.class_list << class_data puts "\t#{student.name}, you have been accepted for the #{class_data[:name]} class." end end end class Student < Registrar attr_reader :name attr_reader :id attr_reader :gpa attr_accessor :class_list def initialize(id,name,gpa) @name = name @id = id @gpa = gpa @class_list = [] end def list_classes list = [] class_list.each do |item| list << item[:name] end return list.join(",") end def to_s return "ID: #{id} Name: #{name} GPA: #{gpa} Classes: #{list_classes}" end def apply_for_class(class_data) handle_application(self,class_data) end end registrar = Registrar.new 100.upto(104) do |n| student = registrar.get_student_data(n) puts "Student #{student.name} applying for classes ..." Registrar::Classes.each do |class_data| student.apply_for_class(class_data) end puts "Student data:" puts "\t#{student}\n\n" end ------------------------------------ Try running this program, and examine how it works. It shows very simply how a class hierarchy can handle communication between objects (and it should be obvious how one student object could communicate to any other student object by way of the registrar class). -- Paul Lutus http://www.arachnoid.com