Search code examples
smalltalksqueak

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?


Solution

  • 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.