3 ms·
The idea is to replace "calling a function" with "sending a message". Traditionally a function call is fixed at compile time (with some exceptions such as func
by pdkl95 10y ago
The idea is to replace "calling a function" with "sending a message".
Traditionally a function call is fixed at compile time (with some exceptions such as function pointers). In C a function is just an address; if we want to call foo(), we must have that function available at address &foo. C++ added flexibility by allowing there to be multiple functions called foo() with and a set of vtables[1] that store the actual (C-style) address. Other variations exist, but all of these traditional styles map function calls to specific code that runs every time the function is called.
Message change all of that. Instead of vtables (or similar)
obj = create_foo()
# instead of calling foo's bar() function directly, e.g.
foo_bar(obj)
# or perhaps
obj.bar()
... we send a message by name of the function we want to call to the object itself
obj = create_foo()
obj.send_message("bar")
# if function args are needed, include them as an array
obj.send_message("baz", [42, "quux"])
The idea is that while the message can be effectively the same as a function call, it doesn't have to be. In a proper OO language, this message sending is handled automagically by the syntax.
# instead of handling the messages directly, e.g.
obj.send_message("bar")
# the language does that for you when you call
obj.bar()
# in some languages, these are equivalent
In many cases the "foo" class above will handle the message "bar" by running the appropriate function, but that isn't required. For example, in ruby when no function exists for a given message, the raw message is send to the #method_missing function.
class Foo
def method_missing(name, *args, &block)
puts "#{self.inspect} I was sent message #{name.inspect} with args #{args.inspect}"
end
end
>> obj = Foo.new
=> #<Foo>
>> obj.bar()
#<Foo> I was sent message :bar with args []
=> nil
>> obj.any_name_we_want()
#<Foo> I was sent message :any_name_we_want with args []
=> nil
>> obj.any_name_we_want("args", "are", "optional")
#<Foo> I was sent message :any_name_we_want with args ["args", "are", "optional"]
Thinking of "obj.method()" as a message instead of only a function is much more flexible.
[1] https://en.wikipedia.org/wiki/Virtual_method_table https://en.wikipedia.org/wiki/Virtual_method_table
- stinos 10y agothanks, that was a nice explanation