[Tutor] methods and functions
Alan Gauld
alan.gauld@blueyonder.co.uk
Fri Jun 13 15:08:02 2003
> methods were the same thing as functions. I was told
> this was not the case, but every example I was given.
> it looked to me that when a method was called for an
> instance, it just like calling a function.
In most OO languages a method translates to a function call,
but it isn't the case in every OO language. Let me try to
explain and illustrate:
In principle objects get sent messages and as a result
execute some operation. The block of code that is executed
in response to a message is the corresponding method. Now
there is nothing in OO theory that says the message and the
method must have the same name. We can use a hypothetical
programming language which looks a bit like python to
illustrate how this might work:
class Spam:
def foo(self): return 42
addMethod("doIt", self.foo)
s = Spam()
s.send("doIt")
Here we create a class and define a method foo. However in this
language the only way to execute methods is by 'send'ing a message
to the class. In this case we say that the message that will
execute foo is called "doIt".
Then we create an instance of Spam called s and send the message
doIt to the object. Internally the send operation of the class
looks up a dictionary to find what method is associated with
the doIt message and then invokes it.
That may seem convoluted compared to the way we do things in
Python (and Java and C++ etc...) but it is how some OO languages
work(examples are Lisp Flavors and LOOPS). The advantage of
this technique is that you can dynamically change which method
gets executed for a given message at runtime, thus if certain
operations are only allowed in a certain state you can create
an error handler and associate it with all messages which are
not permitted when the state is set. The external code just
'sends' the same string value and the object calls the
appropriate method depending on state. This avoids having to
explicitly check the state and have duplicated error code in
each method.
There are some other esoteric advantages but they are less used.
The bottom line is that oit is a good idea to think of them as
different things. Messages are sent to objects and the object
executes a method. The fact that the code looks like a functon
call, and usually acts like a function call is just a lucky
coincidence!
HTH,
Alan G.