Search code examples
oopsmalltalkpharosqueakvisualworks

Why do methods return "self" by default in Smalltalk?


Background

In Smalltalk, if you don't excplicitly return anything then the message passing evaluates to the receiver (or "self" in the message context).

For example, given this method:

MyClass >> myMethod
  Transcript show: 'hello'; cr.

Evaluating (doint "print-it") this:

| myInstance |
myInstance := MyClass new.
myInstance myMethod.

If <print-it> is done to the last invocation, then the result would be the instance itself.

Questions

  • Why was this designed this way?
  • What is the idea behind it?
  • What was the philosophical background?
  • What are the practical benefits from it? Is it to facilitate method chaining?

Solution

  • One very simple reason has not been stated yet: In the Virtual Machine, returning self is simpler and more efficient than returning any other object.

    Smalltalk byte codes implement a stack machine. That means arguments are passed by pushing them onto a stack, rather than putting them into registers. In addition to the arguments as listed in the method signature, a hidden argument is always passed, which is the receiver of the message. So even for unary methods (those without arguments) the receiver is pushed onto the stack, then the method is executed, and the receiver value on the stack is how the method knows "self". By returning "self" if no explicit return statement is given, the VM can just leave the "self" oop on the stack, which saves at least one memory store operation. So from an efficiency and simplicity standpoint, returning "self" is the most elegant thing to do.