Hello. In this session, we will talk about class methods.
In Pharo, everything is an object,
and you can send messages to objects.
So if you take these two pieces of information,
classes are objects too,
and you can send information, hence messages to classes.
I'll give you two examples.
Time now: you send the message now to the object Time which is a class.
And it returns the current time.
So I send the message now
to the object Time which is a class name.
It sends me back the current time.
Likewise, I send the message today to the object Date which is a class;
it returns the date.
I'll give three more examples.
I send the message workingDirectory to the class FileLocator;
it returns the current path,
the file where the execution takes place.
In the second example,
I send the message getPng to the object ZnEasy
with the URL of a png file as the argument.
It returns the png file which was previously downloaded.
In the third example,
I send the message startDefaultOn to ZnServer which is a class again,
with a port number.
This will start the HTTP server.
So in the three cases, you send a message to one class.
How do you implement a class method?
You select the class
and click on the button Class to say you want to implement a method
on the class side and not on the instance side.
And you implement a method like usual.
So the method today is implemented on the class side,
in the class Date.
On this slide, you can see a common mistake.
Here, you wish to send the message withValue
to the class Counter;
to return a new Counter with a value set as a parameter.
So you want
Counter withValue: 10 to return a new Counter which starts with value 10.
If I evaluate this expression, I get the value Counter,
not a new counter.
In fact, I get the class, not a new instance of this class.
Why this mistake? What's the problem?
The problem is that by default, all methods return self.
So if I don't specify the value to return, the method will return self.
So the code up here is equivalent to the code down there.
In this case, self is the class Counter.
So the method returns the class itself, not the instance created just above.
To correct this problem,
simply add a caret
in front of self new.
To summarize, classes are objects.
You can send messages to any objects, so you can send them to any classes too.
To implement the corresponding methods,
you need to press the button Class after selecting a class.
Most class methods create not only new instances
but also other things.
You will see lots of other uses of class methods in Pharo.
Class methods are just like other methods;
there are no particular rules.
The lookup works exactly in the same way.
We will learn about it next week.