2 ms·
Message passing OO like in Ruby and Smalltalk means that an object receives messages that it can interpret in any way it wants. For example you can create an ob
by jules 15y ago
Message passing OO like in Ruby and Smalltalk means that an object receives messages that it can interpret in any way it wants. For example you can create an object that prints the messages to the console:
class Foo
def method_missing(meth, *args)
puts "#{meth}(#{args.join(',')})"
end
end
f = Foo.new
f.foo() # prints foo()
f.bar(1,2) # prints bar(1,2)
f[2] = "hello" # prints []=("hello")
You can't do this with CLOS because methods are lexically scoped.
Why is this interesting? For example because with this you can implement transparent remote objects. When you make a call on the object, it makes a network request, on the other computer the call is made and the result is sent back over the network, and finally the original method call returns. So the code would end up looking something like this:
# server on ip 1.2.3.4
shared_object = Array.new
shared_object[3] = "good morning"
serve_object("foo", shared_object)
# client
remote_object = RemoteObject.new("1.2.3.4", "foo")
remote_object.length # makes a network call to 1.2.3.4 and computes the length
remote_object[3] # returns "good morning"
remote_object[3] = "hello" # sets the index 3 to the string "hello"
# code in the server can now access shared_object[3] and it will get "hello"
Ruby actually has such a library. It's called Drb.
All in all, I think that generic functions are better than message passing, but generic functions are definitely not strictly more powerful.