Methods and Classes, the same?
We are used to think of classes and methods as distinct concepts. Whereas in fact, they are two of the same kind. A class is a static template for runtime objects, a method is a static template for runtime activation records (or stack frames, if you want).
-
p = new Person("Joe", "Random");The code above allocates memory for a new object, with enough space for each field of a person. Executes the body of person’s constructor with the given parameters. And eventually returns a reference to the allocated memory.
-
bool = set.contains(p);
The code above allocates memory for a new stack frame, with enough space for each local variable of the #contains method. Executes the body of #contains with the given parameters. And eventually returns a reference to the result of the executed code.
As you see, the only major difference between class creation and method call is the kind of their return value.
If we take a deeper look, each stack frame has a pointer to its origin. The origin is given by the static context. Each method is statically enclosed in a class, thus the origin points to the receiving instance of the method call. This allows the method to access fields of the enclosing class. The same applies for objects. Take for example Java’s inner classes, they keep a pointer to an instance of their outer class. This allows inner classes to access fields of the enclosing class.
Of course, I am not the first to observe the uniformity of classes and methods. I am standing on the shoulder of giants such as Kristen Nygaard and Dave Ungar, the creators of BETA and Self respectively. Both of these languages unify classes and methods in a more general concept. BETA is class based and uses patterns is its sole abstraction. Self is prototype based and uses, unsurprisingly, prototypes as its sole abstraction.
For further reading, please refer to the HOPL papers of BETA and Self respectively.
PS, is the hammer shown on the BETA page actually the language’s logo? That would make it the language with the possibly most cool logo of all times…
July 26th, 2009 at 04:09
s/#add/#contains/g
July 26th, 2009 at 07:31
Done, thank you!