Ohad
Ohad

Reputation: 1651

How do we call a class method from another class method?

what is the correct way calling a class method from another class method?

is it

  className methodName

or

   self methodName

or

    className class methodName

can we use self when we don't create an instance of the class?

Upvotes: 1

Views: 3303

Answers (2)

Uko
Uko

Reputation: 13396

You want to use self methodName if you are calling it from the same class. In Smalltalk class is an object itself, so self methodName in a class method sends message to self i.e. class object.

This is good also to maintain consistency during inheritance. Imagine that you have SuperClass and SubClass. Then if you use self methodName somewhere in SuperClass, then in SubClass it will be equivalent to SubClass methodName because the object executing the method will be SubClass object. Now if you hardcode SuperClass methodName then it will be the same in subclasses, and this is probably not what you are expecting.

If you will do className class methodName you will send a message to className class object, which is an instance of Metaclass, an this is probably completely different from what you expect.

Here is a picture showing the core concept of Smalltalk hierarchy. (hollow arrows are inheritance).

Smalltalk class hierarchy

Long story short:

If you have

SomeClass class >> #someMethod
    "do something"

Then you should use

SomeClass class >> #otherMethod
    self someMethod

or

OtherClass class >> #otherMethod
    SomeClass someMethod

Second will work for first case, but out of design point of view first is usually better.

Upvotes: 3

Sean DeNigris
Sean DeNigris

Reputation: 6390

Using self is considered better because you avoid duplicating the class name everywhere. As far as whether the other ones work, try and let us know ;) It would be more effective to compile and run a one line method in your image than to ask on SO!! Exploration and experimentation are part of what Smalltalk is all about - use the force, Luke :)

Upvotes: 1

Related Questions