Sunday, December 15, 2013

Private Methods in Pharo

The nice thing on Smalltalk is that it is extensible without having to ask a language vendor.
Using this Camille Teruel created a small proof-of concept for adding private methods to Pharo.

Load the project "PrivateMethods" into your Pharo image. I tried with  Pharo3.0 Latest update: #30639.

Now create a new class

Object subclass: #Bar
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Foo'


Then implement a method that you mark as private using the pragma <private>

foo
<private>

^42

If you try to evaluate 

  Bar new foo

you will get the usual "Message not understood" as it is private.

But nonetheless you can call it from other private or public methods. Just implement a Bar>>bar method:

     bar
        "Call the private method"
^self foo

and evaluate

     Bar new bar

to get the answer to life, universe and everything ...

To make sure it is really private (instead of protected) just implement a subclass and call it from a subclass method. You will see it works.

1 comment:

Damien Cassou said...

Thanks for the post. However, the pragma is not visible in your blog post.