Hello everyone.
In this course, we'll learn about the method Yourself.
It is seemingly useless, and yet it's very useful.
Let's start with an exercise.
For this expression, Set new add: 2,
we'd like to get a set containing the value 2
so that it returns only the value 2.
Why do you get the value 2 rather than a set containing 2?
If you look at the method add: implemented in the class Set,
you can see it returns its parameter.
In the expression Set new add: 2,
the expression Set returns the class Set.
When you send new to the class Set, it returns a new set.
Set new add: 2
returns the value returned by add: 2, which is 2.
The set is lost.
To solve this problem,
you can describe the expressions step by step.
You can create a temporary variable: you declare the variable s.
Assign the new Set to s.
Add 2 to s.
s now contains a set which contains the value 2.
It's what we wanted.
You can simplify these expressions
by using the method yourself.
If you take a closer look,
you'll see it contains only one thing: return self.
Return self being optional, this method could also be empty
and do nothing except returning its receiver.
This method seemingly only returns its receiver.
And yet, it's useful in such cases
thanks to the operator cascade.
After adding 2,
let's execute the method yourself
which will return the receiver
so that the full expression can be the receiver,
which is the new Set.
If I take Set new,
which is the new Set,
and write add: 2 applied to Set new,
it returns 2.
But thanks to the operator cascade followed by yourself,
the expression as a whole returns the new Set.
Why does the cascade systematically return
the value its last expression returns?
The cascade, in this case,
returns the value yourself returns.
We often use yourself and the cascade
in the methods of instantiation.
These are class methods
of messages to be sent to classes
which return new instances.
To create a new Set
which contains an object by default,
I can send the message with: anObject to Set.
This code is executed to create a new Set,
to put it in the variable instance,
to add to instance the new parameter,
and to return instance.
I can write this expression as a whole by using yourself
in a shorter and more idiomatic way.
This code is typically found in Pharo.
It's important to master the semicolon,
the cascade, and yourself.
What you must remember at the end of this course
is that some methods, even though they're very simple,
can be very powerful and used a lot.
The cascade, the semicolon, and the method yourself
are very often used together
to make sure a complete expression
returns the expected value.