Search code examples
smalltalkpharosqueakvisualworksamber-smalltalk

What is the difference between self and yourself in Smalltalk?


In Smalltalk, there are two terms often found within a method body: self and yourself.

What is the difference between them?


Solution

  • The reserved word self is a pseudo variable (you cannot assign to it) that refers to the current receiver of the method where it is used. On the other side yourself is a message you can send to any object to get that very same object.

    The implementation of yourself is

    yourself
        ^self
    

    meaning that the message yourself will behave as I just explained.

    The reason why yourself exists is to support message cascading, where you put it as the last message to make sure the resulting expression will answer with the receiver:

    ^receiver
       msg1;
       msg2;
       yourself
    

    If msg2 might answer with something different from the receiver you can append the yourself message to ignore that answer and return receiver instead. Of course you could have achieved the same result by writing:

    receiver
       msg1;
       msg2.
    ^receiver
    

    Because of the simplicity of these two examples, it might be hard to understand what the advantage would be. However, consider that receiver is not a variable but a complex expression, something like.

    ^(self msg: arg1 arg: arg2)
       msg1;
       msg2;
       yourself.
    

    Without using yourself you would have to add a temporary to save the value of the receiver to achieve the same:

    | answer |
    answer := self msg: arg1 arg: arg2.
    answer
       msg1;
       msg2.
    ^answer
    

    which is a little bit more verbose.

    To summarize, self is a reserved word that refers to the current receiver and yourself is just a regular method that is there just for convenience.