# Pharo by Example 5

Stéphane Ducasse, Dimitris Chloupis, Nicolai Hess, Dmitri Zagidulin, Andrew P. Black, Oscar Nierstrasz, Damien Pollet, Damien Cassou, Marcus Denker

► To cite this version:

Stéphane Ducasse, Dimitris Chloupis, Nicolai Hess, Dmitri Zagidulin, Andrew P. Black, et al., Pharo by Example 5. Lulu.com & Square Bracket Associates, pp.1-358, 2017, 978-1-365-65459-6. hal-01659495

HAL Id: hal-01659495

https://inria.hal.science/hal-01659495

Submitted on 8 Dec 2017

HAL is a multi-disciplinary open access
archive for the deposit and dissemination of sci-
entific research documents, whether they are pub-
lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d'enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.

<figure><img src="image_1.png" /></figure>
Pharo by Example 5

Stéphane Ducasse
Dimitris Chloupis
Nicolai Hess
Dmitri Zagidulin

January 14, 2017
commit 7a4b6fc*
Copyright 2016 by Stéphane Ducasse, Dimitris Chloupis, Nicolai Hess and Dmitri Zagidulin. Copyright 2009 by Andrew P. Black, Stéphane Ducasse, Oscar Nierstrasz, Damien Pollet, Damien Cassou and Marcus Denker. The contents of this book are protected under the Creative Commons Attribution-ShareAlike 3.0 Unported license.

You are free:

• to Share: to copy, distribute and transmit the work,

• to Remix: to adapt the work,

Under the following conditions:

**Attribution.** You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).

**Share Alike.** If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license.

For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page:

http://creativecommons.org/licenses/by-sa/3.0/

Any of the above conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights.

<figure><img src="image_2.png" /></figure>

Your fair dealing and other rights are in no way affected by the above. This is a human-readable summary of the Legal Code (the full license):

http://creativecommons.org/licenses/by-sa/3.0/legalcode

<figure><img src="image_3.png" /></figure>

Published by Lulu.com & Square Bracket Associates.

http://squarebracketassociates.org

ISBN 978-1-365-65459-6

First Edition, January 2017.

Book layout and typography based on the sbabook LATEX class by Damien Pollet.
# Contents

## Contents

i

### 1 Preface

1

1.1 What is Pharo? 1

1.2 Who should read this book? 2

1.3 A word of advice 3

1.4 An open book 3

1.5 The Pharo community 3

1.6 Examples and exercises 4

1.7 Acknowledgments 4

1.8 Hyper special acknowledgments 4

### 2 A quick tour of Pharo

7

2.1 Installing Pharo 7

2.2 Pharo: File components 8

2.3 Launching Pharo 9

2.4 PharoLauncher 10

2.5 The World Menu 11

2.6 Sending messages 13

2.7 Saving, quitting and restarting a Pharo session 15

2.8 Playgrounds and Transcripts 15

2.9 Keyboard shortcuts 16

2.10 The System Browser 19

2.11 Finding classes 22

2.12 Finding methods 25

2.13 Defining a new method 27

2.14 Chapter summary 31

### 3 A first application

33

3.1 The Lights Out game 34

3.2 Creating a new Package 34

3.3 Defining the class L0Cell 35

3.4 Adding methods to a class 37

3.5 Inspecting an object 39

3.6 Defining the class L0Game 41

3.7 Organizing methods into protocols 46

i
<table><tbody><tr><td>3.8</td><td>Finishing the game</td><td>47</td></tr><tr><td>3.9</td><td>Let's try our code</td><td>49</td></tr><tr><td>3.10</td><td>Saving and sharing Pharo code</td><td>51</td></tr><tr><td>3.11</td><td>Chapter summary</td><td>56</td></tr><tr><td><b>4</b></td><td><b>Syntax in a nutshell</b></td><td><b>57</b></td></tr><tr><td>4.1</td><td>Syntactic elements</td><td>57</td></tr><tr><td>4.2</td><td>Pseudo-variables</td><td>60</td></tr><tr><td>4.3</td><td>Message sends</td><td>61</td></tr><tr><td>4.4</td><td>Method syntax</td><td>62</td></tr><tr><td>4.5</td><td>Block syntax</td><td>63</td></tr><tr><td>4.6</td><td>Conditionals and loops in a nutshell</td><td>64</td></tr><tr><td>4.7</td><td>Primitives and pragmas</td><td>66</td></tr><tr><td>4.8</td><td>Chapter summary</td><td>67</td></tr><tr><td><b>5</b></td><td><b>Understanding message syntax</b></td><td><b>69</b></td></tr><tr><td>5.1</td><td>Identifying messages</td><td>69</td></tr><tr><td>5.2</td><td>Three types of messages</td><td>71</td></tr><tr><td>5.3</td><td>Message composition</td><td>74</td></tr><tr><td>5.4</td><td>Hints for identifying keyword messages</td><td>79</td></tr><tr><td>5.5</td><td>Expression sequences</td><td>81</td></tr><tr><td>5.6</td><td>Cascaded messages</td><td>81</td></tr><tr><td>5.7</td><td>Chapter summary</td><td>82</td></tr><tr><td><b>6</b></td><td><b>The Pharo object model</b></td><td><b>85</b></td></tr><tr><td>6.1</td><td>The rules of the model</td><td>85</td></tr><tr><td>6.2</td><td>Everything is an Object</td><td>85</td></tr><tr><td>6.3</td><td>Every object is an instance of a class</td><td>86</td></tr><tr><td>6.4</td><td>Instance structure and behavior</td><td>87</td></tr><tr><td>6.5</td><td>The instance side and the class side</td><td>88</td></tr><tr><td>6.6</td><td>Every class has a superclass</td><td>94</td></tr><tr><td>6.7</td><td>Everything happens by sending messages</td><td>97</td></tr><tr><td>6.8</td><td>Method lookup follows the inheritance chain</td><td>99</td></tr><tr><td>6.9</td><td>Shared variables</td><td>105</td></tr><tr><td>6.10</td><td>Internal object implementation note</td><td>109</td></tr><tr><td>6.11</td><td>Chapter summary</td><td>110</td></tr><tr><td><b>7</b></td><td><b>Some of the key tools of the Pharo environment</b></td><td><b>113</b></td></tr><tr><td>7.1</td><td>Pharo environment overview</td><td>113</td></tr><tr><td>7.2</td><td>The main code browser</td><td>115</td></tr><tr><td>7.3</td><td>The inspector</td><td>128</td></tr><tr><td>7.4</td><td>The debugger</td><td>130</td></tr><tr><td>7.5</td><td>The process browser</td><td>139</td></tr><tr><td>7.6</td><td>Finding methods</td><td>140</td></tr><tr><td>7.7</td><td>Chapter summary</td><td>140</td></tr></tbody></table>
<table><tbody><tr><td><strong>8</strong></td><td><strong>Sharing code and source control</strong></td><td><strong>141</strong></td></tr><tr><td>8.1</td><td>Packages: groups of classes and methods</td><td>141</td></tr><tr><td>8.2</td><td>Source control</td><td>148</td></tr><tr><td>8.3</td><td>The File List Browser</td><td>151</td></tr><tr><td>8.4</td><td>In Pharo, you can't lose code</td><td>152</td></tr><tr><td>8.5</td><td>Chapter summary</td><td>153</td></tr><tr><td><strong>9</strong></td><td><strong>SUnit</strong></td><td><strong>155</strong></td></tr><tr><td>9.1</td><td>Introduction</td><td>155</td></tr><tr><td>9.2</td><td>Why testing is important</td><td>156</td></tr><tr><td>9.3</td><td>What makes a good test?</td><td>157</td></tr><tr><td>9.4</td><td>SUnit by example</td><td>158</td></tr><tr><td>9.5</td><td>The SUnit cookbook</td><td>162</td></tr><tr><td>9.6</td><td>The SUnit framework</td><td>163</td></tr><tr><td>9.7</td><td>Advanced features of SUnit</td><td>166</td></tr><tr><td>9.8</td><td>Continuing after a failure</td><td>168</td></tr><tr><td>9.9</td><td>SUnit implementation</td><td>168</td></tr><tr><td>9.10</td><td>A piece of advices on testing</td><td>171</td></tr><tr><td>9.11</td><td>Chapter summary</td><td>172</td></tr><tr><td><strong>10</strong></td><td><strong>Basic classes</strong></td><td><strong>175</strong></td></tr><tr><td>10.1</td><td>Object</td><td>175</td></tr><tr><td>10.2</td><td>Numbers</td><td>184</td></tr><tr><td>10.3</td><td>Characters</td><td>188</td></tr><tr><td>10.4</td><td>Strings</td><td>189</td></tr><tr><td>10.5</td><td>Booleans</td><td>190</td></tr><tr><td>10.6</td><td>Chapter summary</td><td>192</td></tr><tr><td><strong>11</strong></td><td><strong>Collections</strong></td><td><strong>193</strong></td></tr><tr><td>11.1</td><td>Introduction</td><td>193</td></tr><tr><td>11.2</td><td>The varieties of collections</td><td>193</td></tr><tr><td>11.3</td><td>Collection implementations</td><td>196</td></tr><tr><td>11.4</td><td>Examples of key classes</td><td>197</td></tr><tr><td>11.5</td><td>Collection iterators</td><td>209</td></tr><tr><td>11.6</td><td>Some hints for using collections</td><td>213</td></tr><tr><td>11.7</td><td>Chapter summary</td><td>214</td></tr><tr><td><strong>12</strong></td><td><strong>Streams</strong></td><td><strong>217</strong></td></tr><tr><td>12.1</td><td>Two sequences of elements</td><td>217</td></tr><tr><td>12.2</td><td>Streams vs. collections</td><td>218</td></tr><tr><td>12.3</td><td>Streaming over collections</td><td>219</td></tr><tr><td>12.4</td><td>Using streams for file access</td><td>227</td></tr><tr><td>12.5</td><td>Chapter summary</td><td>229</td></tr><tr><td><strong>13</strong></td><td><strong>Morphic</strong></td><td><strong>231</strong></td></tr><tr><td>13.1</td><td>The history of Morphic</td><td>231</td></tr><tr><td>13.2</td><td>Manipulating morphs</td><td>233</td></tr></tbody></table>
<table><tbody><tr><td>13.3</td><td>Composing morphs</td><td>234</td></tr><tr><td>13.4</td><td>Creating and drawing your own morphs</td><td>236</td></tr><tr><td>13.5</td><td>Interaction and animation</td><td>239</td></tr><tr><td>13.6</td><td>Interactors</td><td>242</td></tr><tr><td>13.7</td><td>Drag-and-drop</td><td>243</td></tr><tr><td>13.8</td><td>A complete example</td><td>245</td></tr><tr><td>13.9</td><td>More about the canvas</td><td>250</td></tr><tr><td>13.10</td><td>Chapter summary</td><td>251</td></tr><tr><td><b>14</b></td><td><b>Seaside by example</b></td><td><b>253</b></td></tr><tr><td>14.1</td><td>Why do we need Seaside?</td><td>253</td></tr><tr><td>14.2</td><td>Getting started</td><td>254</td></tr><tr><td>14.3</td><td>Seaside components</td><td>260</td></tr><tr><td>14.4</td><td>Rendering HTML</td><td>264</td></tr><tr><td>14.5</td><td>CSS: Cascading style sheets</td><td>270</td></tr><tr><td>14.6</td><td>Managing control flow</td><td>272</td></tr><tr><td>14.7</td><td>A complete tutorial example</td><td>278</td></tr><tr><td>14.8</td><td>A quick look at AJAX</td><td>285</td></tr><tr><td>14.9</td><td>Chapter summary</td><td>288</td></tr><tr><td><b>15</b></td><td><b>Classes and metaclasses</b></td><td><b>291</b></td></tr><tr><td>15.1</td><td>Rules for classes and metaclasses</td><td>291</td></tr><tr><td>15.2</td><td>Revisiting the Pharo object model</td><td>292</td></tr><tr><td>15.3</td><td>Every class is an instance of a metaclass</td><td>293</td></tr><tr><td>15.4</td><td>The metaclass hierarchy parallels the class hierarchy</td><td>295</td></tr><tr><td>15.5</td><td>Every metaclass inherits from Class and Behavior</td><td>297</td></tr><tr><td>15.6</td><td>Every metaclass is an instance of Metaclass</td><td>300</td></tr><tr><td>15.7</td><td>The metaclass of Metaclass is an instance of Metaclass</td><td>300</td></tr><tr><td>15.8</td><td>Chapter summary</td><td>302</td></tr><tr><td><b>16</b></td><td><b>Reflection</b></td><td><b>303</b></td></tr><tr><td>16.1</td><td>Introspection</td><td>304</td></tr><tr><td>16.2</td><td>Browsing code</td><td>309</td></tr><tr><td>16.3</td><td>Classes, method dictionaries and methods</td><td>311</td></tr><tr><td>16.4</td><td>Browsing environments</td><td>313</td></tr><tr><td>16.5</td><td>Accessing the run-time context</td><td>315</td></tr><tr><td>16.6</td><td>Intercepting messages not understood</td><td>318</td></tr><tr><td>16.7</td><td>Objects as method wrappers</td><td>322</td></tr><tr><td>16.8</td><td>Pragmas</td><td>325</td></tr><tr><td>16.9</td><td>Chapter summary</td><td>326</td></tr><tr><td><b>17</b></td><td><b>Regular expressions in Pharo</b></td><td><b>329</b></td></tr><tr><td>17.1</td><td>Tutorial example — generating a site map</td><td>330</td></tr><tr><td>17.2</td><td>Regex syntax</td><td>338</td></tr><tr><td>17.3</td><td>Regex API</td><td>345</td></tr><tr><td>17.4</td><td>Implementation Notes by Vassili Bykov</td><td>351</td></tr><tr><td>17.5</td><td>Chapter Summary</td><td>351</td></tr></tbody></table>
# Preface

## 1.1 What is Pharo?

Pharo is a modern, open-source, dynamically typed language supporting live coding inspired by Smalltalk. Pharo and its ecosystems is composed of the six fundamental elements:

* A dynamically-typed language with a syntax so simple it can fit on a postcard and yet is readable even for someone not familiar with it.

* A live coding environment that allows the coder to modify its code while the code executes, without any need to slow down his or her workflow.

* A powerful IDE providing all the tools to help manage complex code and promote good code design.

* A rich library that creates an environment so powerful that it can be viewed even as a virtual OS, including a very fast JITing VM and full access to OS libraries and features via its FFI.

* A culture where changes and improvements are encouraged and highly valued.

* A community that welcomes coders from any corner of the world with any skill and any programming languages.

Pharo strives to offer a lean, open platform for professional software development, as well as a robust and stable platform for research and development into dynamic languages and environments. Pharo serves as the reference implementation for the Seaside web development framework available at http://www.seaside.st.
Pharo core contains only code that has been contributed under the MIT license. The Pharo project started in March 2008 as a fork of Squeak (a modern implementation of Smalltalk-80), and the first 1.0 beta version was released on July 31, 2009. The current version is Pharo 5.0, released in May 2016. Pharo 6.0 is in alpha development and planned for release in April 2017.

Pharo is highly portable. Pharo can run on OS X, Windows, Linux, Android, iOS, and Raspberry Pi. Its virtual machine is written entirely in a subset of Pharo itself, making it easy to simulate, debug, analyze, and change from within Pharo itself. Pharo is the vehicle for a wide range of innovative projects, from multimedia applications and educational platforms to commercial web development environments.

There is an important principle behind Pharo: Pharo doesn't just copy the past, but it reinvents the essence behind Smalltalk. However we realize that Big Bang style approaches rarely succeed. Pharo instead favors evolutionary and incremental changes. Rather than leaping for the final perfect solution in one big step, a multitude of small changes keeps even the bleeding edge relatively stable while experimenting with important new features and libraries. This facilitates rapid feedback and contributions from the community, on which Pharo depends for its success. Finally Pharo is not read-only, Pharo integrates changes made by the community, daily. Pharo got 100 contributors from all over the world. You can have an impact on Pharo, too!

## 1.2 Who should read this book?

The previous revision of this book was based on Pharo 1.4. This revision has been liberally updated to align with Pharo 5.0. Various aspects of Pharo are presented, starting with the basics then proceeding to intermediate topics. Advanced topics are presented in Deep into Pharo, a book on the internals of Pharo that is freely available at http://books.pharo.org. In addition for readers interested in web development, a new book Enterprise Pharo: a Web Perspective is freely available at http://books.pharo.org.

This book will not teach you how to program. The reader should have some familiarity with programming languages. Some background with object-oriented programming would also be helpful.

This book will introduce the Pharo programming environment, the language and the associated tools. You will be exposed to common idioms and practices, but the focus is on the technology, not on object-oriented design. Wherever possible, we will show you lots of examples.

There are numerous other books on Smalltalk freely available on the web at http://stephane.ducasse.free.fr/FreeBooks.html.
## 1.3 A word of advice

Do not be frustrated by parts of Pharo that you do not immediately understand. You do not have to know everything! Alan Knight expresses this as follows:

> *Try not to care.* Beginning Smalltalk programmers often have trouble because they think they need to understand all the details of how a thing works before they can use it. This means it takes quite a while before they can master Transcript show: 'Hello World'. One of the great leaps in OO is to be able to answer the question "How does this work?" with "I don't care".

When you don't understand something, simple or complex, do not hesitate for a second to ask us at our mailing lists (pharo-users@lists.pharo.org or pharo-dev@lists.pharo.org), IRC and Slack. We love questions and we welcome people of any skill.

## 1.4 An open book

This book is an open book in the following senses:

* The content of this book is released under the Creative Commons Attribution-ShareAlike (by-sa) license. In short, you are allowed to freely share and adapt this book, as long as you respect the conditions of the license available at the following URL http://creativecommons.org/licenses/by-sa/3.0/.

* This book just describes the core of Pharo. We encourage others to contribute chapters on the parts of Pharo that we have not described. If you would like to participate in this effort, please contact us. We would like to see more books around Pharo!

* It is also possible to contribute directly to this book via Github. Just follow the instructions there and ask any question on the mailing list. You can find the Github repo at https://github.com/SquareBracketAssociates/UpdatedPharoByExample

## 1.5 The Pharo community

The Pharo community is friendly and active. Here is a short list of resources that you may find useful:

* http://www.pharo.org is the main web site of Pharo.

* On IRC, you can find us on the freenode.net server, channel "pharo".
* SmalltalkHub (http://www.smalltalkhub.com/) is the equivalent of Source-Forge/Github for Pharo projects. Many extra packages and projects for Pharo live there.

* Pharo is also active on Slack - a platform for chat based on IRC (http://pharoproject.slack.com), just ask for an invitation at http://slackinvites.pharo.org. Everybody is welcomed.

## 1.6 Examples and exercises

We have tried to provide as many examples as possible. In particular, there are many examples that show a fragment of code which can be evaluated. We use a long arrow to indicate the result you obtain when you select an expression and from its context menu choose **print it**:

```
3 + 4
>>> 7 "if you select 3+4 and 'print it', you will see 7"
```

In case you want to play with these code snippets in Pharo, you can download a plain text file with all the example code from the Resources sidebar of the book's web site: http://books.pharo.org.

## 1.7 Acknowledgments

We would like to thank Alan Kay, Dan Ingalls and their team for making Squeak, an amazing Smalltalk development environment, that became the open-source project from which Pharo took roots. Pharo also would not be possible without the incredible work of the Squeak developers.

We would also like to thank Hilaire Fernandes and Serge Stinckwich who allowed us to translate parts of their columns on Smalltalk, and Damien Cassou for contributing the chapter on Streams. We especially thank Alexandre Bergel, Orla Greevy, Fabrizio Perin, Lukas Renggli, Jorge Ressia and Erwann Wernli for their detailed reviews.

We thank the University of Bern, Switzerland, for graciously supporting this open-source project and for hosting the web site of this book.

We also thank the Pharo community for their enthusiastic support of this book project, as well as for all the translations of the first edition of **Pharo by Example**.

## 1.8 Hyper special acknowledgments

We want to thank the original authors of this book! Without this initial version it would have been difficult to make this one. Pharo by Example is a central book to welcome newcomers and it has a great value.
Thanks to Manfred Kröhnert, Markus Schlager, Werner Kassens, Michael OKeefe, Aryeh Hoffman, Paul MacIntosh, Gaurav Singh, Jigyasa Grover, Craig Allen, Serge Stinckwich, avh-on1, Yuriy Timchuk, zio-pietro for the typos and feedback. Special thanks to Damien Cassou and Cyril Ferlicot for their great help in the book update. Finally we want to thank Inria for its steady and important financial support, and the RMoD team members for the constant energy pushing Pharo forward.

Super special thanks to Damien Pollet for this great book template.
<figure><img src="image_4.png" /></figure>
# A quick tour of Pharo

This chapter will take you on a high level tour of Pharo, to help you get comfortable with the environment. There will be plenty of opportunities to try things out, so it would be a good idea if you have a computer handy when you read this chapter.

In particular, you will fire up Pharo, learn about the different ways of interacting with the system, and discover some of the basic tools. You will also learn how to define a new method, create an object and send it messages.

*Note:* Most of the introductory material in this book will work with any Pharo version, so if you already have one installed, you may as well continue to use it. However, since this book is written for Pharo 5.0, if you notice differences between the appearance or behaviour of your system and what is described here, do not be surprised.

## 2.1 Installing Pharo

### Downloading Pharo

Pharo is available as a free download from http://pharo.org/download. Click the button for your operating system to download the appropriate .zip file. For example, the full Pharo 5.0 distribution for OS X will be available at http://files.pharo.org/platform/Pharo5.0-mac.zip.

Once that file is unzipped, it will contain everything you need to run Pharo (this includes the VM, the image, and the sources, as explained below).

**Using handy scripts.** http://files.pharo.org/get/ offers a collection of scripts
to download specific versions of Pharo. This is really handy to automate the
process.

To download the latest 50 full system, use the following snippet.

[ wget -O- get.pharo.org/50+vm | bash ]

Installing Pharo

Pharo does not need to install anything in your system, as it's perfectly ca-
pable of running standalone. Depending on your platform, download the
appropriate zip file, uncompress it in a directory of your choice and now you
are ready to launch Pharo. In case of Ubuntu Linux, there is also the extra
option of installing Pharo via the Pharo PPA. Pharo can be also installed via
the command line.

2.2 Pharo: File components

Pharo consists of four main component files. Although you do not need to deal
with them directly for the purposes of this book, it is useful to understand the
roles they play.

1. The **virtual machine (VM)** is the only component that is different for each operating system. The VM is the execution engine (similar to a JVM). It takes Pharo bytcode that is generated each time user compiles a piece of code, converts it to machine code and executes it. Pharo comes with the Cog VM a very fast JITing VM. The VM executable is named:

• Pharo.exe for Windows;

• pharo for Linux ; and

• Pharo for OSX (inside a package also named Pharo.app).

The other components below are portable across operating systems, and can
be copied and run on any appropriate virtual machine.

2. The **sources** file contains source code for parts of Pharo that don't change frequently. Sources file is important because the image file format stores only objects including compiled methods and their bytecode and not their source code. Typically a new **sources** file is generated once per major release of Pharo. For Pharo 5.0, this file is named **PharoV50.sources**.

3. The **changes** file logs of all source code modifications (especially all the changes you did while programming) since the `.sources` file was generated. Each release provides a near empty file named for the release, for example `Pharo5.0.changes`. This facilitates a per method history for diffs or reverting. It means that even if you did not manage to save the image file on a crash or you just forgot, you can recover your changes from this file. A changes file is always coupled with an image file. They work in pair.
4. The **image** file provides a frozen in time snapshot of a running Pharo system. This is the file where all objects are stored and as such it's a cross platform format. An image file contains the live state of all objects of the system (including classes and compiled methods, since they are objects too) at a given point. An image is a virtual object container. The file is named for the release (like Pharo5.0.image) and it is synched with the Pharo5.0.changes file.

## Image/Change pair

The `.image` and `.changes` files provided by a Pharo release are the starting point for a live environment that you adapt to your needs. As you work in Pharo, these files are modified, so you need to make sure that they are writable. Pay attention to remove the changes and image files from the list of files to be checked by anti-viruses. The `.image` and `.changes` files are intimately linked and should always be kept together, with matching base filenames. Never edit them directly with a text editor, as `.images` holds your live object runtime memory, which indexes into the `.changes` files for the source. It is a good idea to keep a backup copy of the downloaded `.image` and `.changes` files so you can always start from a fresh image and reload your code. However, the most efficient way for backing up code is to use a version control system that will provide an easier and powerful way to back up and track your changes.

## Common setup

The four main component files above can be placed in the same directory, but it's a common practice to put the Virtual Machine and sources file in a separate directory where everyone has read-only access to them.

Do whatever works best for your style of working and your operating system.

## 2.3 Launching Pharo

To start Pharo, do whatever your operating system expects: drag the `.image` file onto the icon of the virtual machine, or double-click the `.image` file, or at the command line type the name of the virtual machine followed by the path to the `.image` file.

* On OS X, double click the Pharo5.0.app bundle in the unzipped download.

* On Linux, double click (or invoke from the command line) the `pharo` executable bash script from the unzipped Pharo folder.

* On Windows, enter the unzipped Pharo folder and double click Pharo.exe.
In general, Pharo tries to "do the right thing". If you double click on the VM, it looks for an image file in the default location. If you double click on an `.` image file, it tries to find the nearest VM to launch it with.

If you have multiple VMs installed on your machine, the operating system may no longer be able to guess the right one. In this case, it is safer to specify exactly which ones you meant to launch, either by dragging and dropping the image file onto the VM, or specifying the image on the command line (see the next section).

## Launching Pharo via the command line

The general pattern for launching Pharo from a terminal is:

```
[<Pharo executable> <path to Pharo image>]
```

**Linux command line.** For Linux, assuming that you're in the unzipped `pharo5.0` folder:

```
[./pharo shared/Pharo5.0.image]
```

**OS X command line.** For OS X, assuming that you're in the directory with the unzipped `Pharo5.0.app` bundle:

```
[Pharo5.0.app/Contents/MacOS/Pharo
   Pharo5.0.app/Contents/Resources/Pharo5.0.image]
```

When using a Pharo bundle, you need to right-click on `Pharo5.0.app` and select 'Show Package Contents' to get access to the image. If you need this often, just download a separated image/changes pair and drop that image into the `Pharo5.0.app`.

**Windows command line.** For Windows, assuming that you're in the unzipped `Pharo5.0` folder:

```
[Pharo.exe Pharo5.0.image]
```

## 2.4 PharoLauncher

PharoLauncher is a tool that helps you download and manage Pharo images. It is very useful for getting new versions of Pharo (as well as updates to the existing versions that contain important bug fixes). It also gives you access to images preloaded with specific libraries that make it very easy to use those tools without having to manually install and configure them.

PharoLauncher can be found on SmalltalkHub at http://smalltalkhub.com/#!
/~Pharo/PharoLauncher together with installation instructions and download
<figure><img src="image_5.png" /><figcaption>Figure 2.1: PharoLauncher - GUI</figcaption></figure>

links depending on your platform. **PharoLauncher** is basically composed of two columns.

After installing PharoLauncher and opening it (like you would do for any Pharo image), you should get a GUI similar to Figure 2.1.

* The left column lists images that live locally on your machine (usually in a shared system folder). You can launch any local image directly (either by double-clicking, or by selecting it and pressing the Launch button). A right-click context menu provides several useful functions like copying and renaming your images, as well as locating them on the file system.

* The right column lists Templates, which are remote images available for download. To download a remote image, select it and click the Create image button (located on the top right, next to the Refresh template list button).

You can use your own local images with **PharoLauncher**, in addition to working with the images you donwloaded. To do so, simply ensure that your .image and its associated .changes files are placed in a folder (with the same name as your image) in your default image location. You can find the location in the **PharoLauncher** settings.

## 2.5 The World Menu

Once Pharo is running, you should see a single large window, possibly containing some open playground windows (see Figure 2.2). You might notice a menu bar, but Pharo mainly makes use of context-dependent pop-up menus.
<figure><img src="image_6.png" /></figure>

<figure><img src="image_7.png" /></figure>

**Figure 2.2:** Clicking anywhere on the Pharo window background activates the World Menu

Clicking anywhere on the background of the Pharo window will display the **World Menu**, which contains many of the Pharo tools, utilities and settings.

At the top of the **World Menu**, you will see a list of several core tools in Pharo, including the System Browser, the Playground, the Monticello package manager, and others. We will discuss them in more detail in the coming chapters.

## Interacting with Pharo

Pharo offers three ways to interact with the system using a mouse or other pointing device.

**click (or left-click):** this is the most often used mouse button, and is normally equivalent to left-clicking (or clicking a single-mouse button without any modifier key). For example, click on the background of the Pharo window to bring up the World menu (Figure 2.2).

**action-click (or right-click):** this is the next most used button. It is used to bring up a contextual menu that offers different sets of actions depending on where the mouse is pointing (see Figure 2.3). If you do not have a multi-button mouse, then normally you will configure the control modifier key to action-click with the mouse button.

**meta-click:** Finally, you may meta-click on any object displayed in the image to activate the "morphic halo", an array of handles that are used to perform operations on the on-screen objects themselves, such as inspecting or resizing them (see Figure 2.4). If you let the mouse linger over a handle, a help balloon
<figure><img src="image_8.png" /><figcaption>**Figure 2.3:** Action Click (right click) brings the contextual menu.</figcaption></figure>

<figure><img src="image_9.png" /><figcaption>**Figure 2.4:** Meta-Clicking on a window opens the Halos</figcaption></figure>

will explain its function. In Pharo, how you meta-click depends on your operating system: either you must hold **Shift-Ctrl** or **Shift-Alt** (on Windows or Linux) or **Shift-Option** (on OS X) while clicking.

## 2.6 Sending messages

In the Pharo window, click on an open space to open the **World Menu**, and then select the **Playground** menu option. The **Playground** tool will open (you may recognize it as the **Workspace** tool, from previous versions of Pharo). We can use **Playground** to quickly execute Pharo code. Enter the following code in it, then right click and select **Do it**:

```
[ ProfStef go.
```

This expression will trigger the Pharo tutorial (as shown in Figure 2.6). It is a simple and interactive tutorial that will teach you the basics of Pharo.

Congratulations, you have just sent your first message! Pharo is based on
<figure><img src="image_10.png" /><figcaption>**Figure 2.5:** Executing an expression is simple with the Do it menu item.</figcaption></figure>

<figure><img src="image_11.png" /><figcaption>**Figure 2.6:** Pharo Tutorial is a simple interactive tutorial to learn about Pharo</figcaption></figure>

the concept of sending messages to objects. The Pharo objects are like your soldiers ready to obey once you send them a message they can understand. We will see how an object can understand a message, later on.

If you talk to Pharoers for a while, you will notice that they generally do not use expressions like *call an operation* or *invoke a method*, as developers do in other programming languages. Instead they will say *send a message*. This reflects the idea that objects are responsible for their own actions and that the method associated with the message is looked up dynamically. When sending a message to an object, the object, and not the sender, selects the appropriate method for responding to your message. In most cases, the method with the same name as the message is executed.

As a user you don't need to understand how each message works, the only thing you need to know is what the available messages are for the objects that interest you. This way an object can hide its complexity, and coding can be kept as simple as possible without losing flexibility.
How to find the available messages for each object is something we will explore later on.

## 2.7 Saving, quitting and restarting a Pharo session

You can exit Pharo at any point, by closing the Pharo window as you do any other application window. Additionally you can use the **World Menu** and select either **Save** and **quit** or **Quit**.

In any case, Pharo will display a prompt to ask you about saving your image. If you do save your image and reopen it, you will see that things are *exactly* as you left them. This happens because the image file stores all the objects (edited text, window positions, added methods... of course since they are all objects) that Pharo has loaded into your memory so that nothing is lost on exit.

When you start Pharo for the first time, the Pharo virtual machine loads the image file that you specified. This file contains a snapshot of a large number of objects, including a vast amount of pre-existing code and programming tools (all of which are objects). As you work with Pharo, you will send messages to these objects, you will create new objects, and some of these objects will die and their memory will be reclaimed (garbage-collected).

When you quit Pharo, you will normally save a snapshot that contains all of your objects. If you save normally, you will overwrite your old image file with the new snapshot. Alternatively, you may save the image under a new name.

As mentioned earlier, in addition to the `.image` file, there is also a `.changes` file. This file contains a log of all the changes to the source code that you have made using the standard tools. Most of the time you do not need to worry about this file at all. As we shall see, however, the `.changes` file can be very useful for recovering from errors, or replaying lost changes. More about this later!

It may seem like the image is the key mechanism for storing and managing software projects, but that is not the case. As we shall see soon, there are much better tools for managing code and sharing software developed by teams. Images are very useful, but you should learn to be very cavalier about creating and throwing away images, since versioning tools like *Monticello* offer much better ways to manage versions and share code amongst developers. In addition, if you need to persist objects, you can use several systems such as *Fuel* (a fast object binary deserializer), *STON* (a textual object deserializer) or a database.

## 2.8 Playgrounds and Transcripts

Let us start with some exercises:
1. Close all open windows within Pharo.

2. Open a Transcript and a Playground/workspace. (The Transcript can be opened from the World > Tools > ... submenu.)

3. Position and resize the transcript and playground windows so that the playground just overlaps the transcript (see Figure 2.7).

You can resize windows by dragging one of the corners. At any time only one window is active; it is in front and has its border highlighted.

**About Transcript.** The Transcript is an object that is often used for logging system messages. It is a kind of *system console*.

**About Playground.** Playgrounds are useful for typing snippets of code that you would like to experiment with. You can also use playgrounds simply for typing any text that you would like to remember, such as to-do lists or instructions for anyone who will use your image.

Type the following text into the playground:

[ Transcript show: 'hello world'; cr. ]

Try double-clicking at various points on the text you have just typed. Notice how an entire word, entire string, or all of the text is selected, depending on whether you click within a word, at the end of the string, or at the end of the entire expression. In particular, if you place the cursor before the first character or after the last character and double-click, you select the complete paragraph.

Select the text you have typed, right click and select Do it. Notice how the text "hello world" appears in the transcript window (See Figure 2.7). Do it again.

## 2.9 Keyboard shortcuts

If you want to evaluate an expression, you do not always have to right click. Instead, you can use keyboard shortcuts shown in menu items. Even though Pharo may seem like a mouse driven environment it contains over 200 shortcuts that allow you operate a variety of tools, as well as the facility to assign a keyboard shortcut to any of the 80000 methods contained in the Pharo image. To have a look at the available shortcuts go to World Menu > System > Keymap Browser.

Depending on your platform, you may have to press one of the modifier keys which are Control, Alt, and Command. We will use CMD in the rest of the book: so each time you see something like CMD-d, just replace it with the appropriate modifier key depending on your OS. The corresponding modifier
<figure><img src="image_12.png" /><figcaption>**Figure 2.7:** Executing an expression: displaying a string in the Transcript.</figcaption></figure>

key in Windows is `CTRL`, and in Linux is either `ALT` or `CTRL`, so each time you see something like `CMD-d`, just replace it with the appropriate modifier key depending on your OS.

In addition to `Do it`, you might have noticed `Do it` and `go`, `Print it`, `Inspect it` and several other options in the context menu. Let's have a quick look at each of these.

## Doing vs. printing

Type the expression `3 + 4` into the playground. Now `Do it` with the keyboard shortcut.

Do not be surprised if you saw nothing happen! What you just did is send the message `+` with argument `4` to the number `3`. Normally the resulting `7` would have been computed and returned to you, but since the playground did not know what to do with this answer, it simply did not show the answer. If you want to see the result, you should `Print it` instead. `Print it` actually compiles the expression, executes it, sends the message `printString` to the result, and displays the resulting string.

Select `3+4` and `Print it` (`CMD-p`). This time we see the result we expect.

```
  3 + 4
>>> 7
```

We use the notation `>>>` as a convention in this book to indicate that a particular Pharo expression yields a given result when you `Print it`.
<figure><img src="image_13.png" /><figcaption>**Figure 2.8:** Inspecting a simple number using Inspect</figcaption></figure>

## Inspect

Select or place the cursor on the line of 3+4, and this time Inspect it (CMD-i).

Now you should see a new window titled "Inspector on a SmallInteger(7)" as shown in Figure 2.8. The inspector is an extremely useful tool that allows you to browse and interact with any object in the system. The title tells us that 7 is an instance of the class SmallInteger. The top panel allows us to browse the instance variables of an object and their values. The bottom panel can be used to write expressions to send messages to the object. Type self squared in the bottom panel of the inspector, and Print it.

The inspector presents specific tabs that will show different information and views on the object depending on the kind of object you are inspecting. Inspect Morph new openInWorld you should get a situation similar to the one of Figure 2.9.

## Other operations

Other right-click options that may be used are the following:

* Do it and go additionally opens a *navigable* inspector on the side of the playground. It allows us to navigate the object structure. Try with the previous expression Morph new openInWorld and navigate the structure.

* Basic Inspect it opens the classic inspector that offers a more minimal GUI and live updates of changes to the object.

* Debug it opens the debugger on the code.
<figure><img src="image_14.png" /><figcaption>**Figure 2.9:** Inspecting a Morph using Inspect</figcaption></figure>

*   **Profile** it profiles the code with the Pharo profile tool which shows how much time is spent for each message sent.

*   **Code search** offers several options provided by System Browser, such as browsing the source code of an expression, searching for senders and implementors, and so on.

## 2.10 The System Browser

The System Browser, also known as "Class Browser", is one of the key tools used for programming. As we shall see, there are several interesting browsers available for Pharo, but this is the basic one you will find in any image. The current implementation of the System Browser is called Nautilus (this is the name of the Jules Verne's submarine).

### Opening the System Browser on a given method

This is not the usual way that we open a browser on a method: we use more advanced tools! Now for the sake of this presentation, execute the following snippet:

```
Nautilus openOnMethod: Integer>>#factorial
```

It will open a system browser on the method `factorial`. We should get a System Browser like in Figure 2.10. The title bar indicates that we are browsing the class `Integer` and its method `factorial`. Figure 2.10 shows the different entities displayed by the browser: packages, classes, protocols, methods and method definition.
<figure><img src="image_15.png" /><figcaption>**Figure 2.10:** The System Browser showing the `factorial` method of class `Integer`</figcaption></figure>

In Pharo, the default System Browser is Nautilus. However, it is possible to have other System Browsers installed in the Pharo enviroment such as AltBrowser. Each System Browser may have its own GUI that may be very different from the Nautilus GUI. From now on, we will use the terms Browser, System Browser and (occasionally) Nautilus interchangeably.

## Navigating using the System Browser

Pharo has **Spotter** (see below) to navigate the system. Now we just want to show you the working flow of the System Browser. Usually with **Spotter** we go directly to the class or the method.

Let us look how to find the `printString` method defined in class `Object`. At the end of the navigation, we will get the situation depicted in 2.11.

**Open the Browser by selecting World > System Browser.** When a new System Browser window first opens, all panes but the leftmost are empty. This first pane lists all known packages, which contain groups of related classes.

**Filter packages.** Type part of the name of the package in the left most filter. It filters the list of packages to be shown in the list under it. Type 'Kern' for
<figure><img src="image_16.png" /><figcaption>**Figure 2.11:** The System Browser showing the `printString` method of class `Object`</figcaption></figure>

example.

**Expand the Kernel package and select the Objects element.** When we select a package, it causes the second pane to show a list of all of the classes in the selected package. You should see the hierarchy of `ProtoObject`

**Select the Object class.** When a class is selected, the remaining two panes will be populated. The third pane displays the protocols of the currently selected class. These are convenient groupings of related methods. If no protocol is selected you should see all methods in the fourth pane.

**Select the printing protocol.** You may have to scroll down to find it. You can also click on the third pane and type `pr`, to typeahead-find the printing protocol. Now select it, and you will see in the fourth pane only methods related to printing.

**Select the `printString` method.** Now we see in the bottom pane the source code of the `printString` method, shared by all objects in the system (except those that override it).

There are much better ways to find a method and we will look at them now.
## 2.11 Finding classes

There are several ways to find a class in Pharo. The first, as we have just seen above, is to know (or guess) what package it is in, and to navigate to it using the browser.

A second way is to send the browse message to the class, asking it to open a browser on itself. Suppose we want to browse the class Point.

### Using the message browse

Type `Point browse` into a playground and Do it. A browser will open on the `Point` class.

### Using CMD-b to browse

There is also a keyboard shortcut `CMD-b` (browse) that you can use in any text pane; select the word and press `CMD-b`. Use this keyboard shortcut to browse the class `Point`.

Notice that when the `Point` class is selected but no protocol or method is selected, instead of the source code of a method, we see a class definition. This is nothing more than an ordinary message that is sent to the parent class, asking it to create a subclass. Here we see that the class `Object` is being asked to create a subclass named `Point` with two instance variables, class variables, and to put the class `Point` in the `Kernel-BasicObjects` package. If you click on the `Comments` button at the bottom of the class pane, you can see the class comment in a dedicated pane.

In addition the system supports the following mouse shortcuts

* `CMD-Click` on a word: open the definition of a class when the word is a class name. You get also the implementors of the message when you click on a selector that is in the body of a method.

* `CMD-Shift-Click` on a word: open a list browser with all the refs of the class when the word is a class name. You get also the senders of the message when you click on a selector that is in the body of a method.

### Using Spotter

The fastest (and probably the coolest) way to find a class is to use **Spotter**. Pressing `Shift+Enter` opens **Spotter**, a very powerful tool for finding classes, methods, and many other related actions. Figure 2.12 shows that we look for `Point`.

**Spotter** offers several possibilities as shown in Figure 2.12. You can specify to **Spotter** the kind of *categories* you are interested in. For example, using `#class`
<figure><img src="image_17.png" /><figcaption>**Figure 2.12:** Opening Spotter</figcaption></figure>

followed by the word you look for, indicates that you are interested in classes.
This is the default so you do not need to type `#class`.

Figure 2.13 shows how we can ask **Spotter** to show all the implementors of a given message. We do not have to type the full category name. Other Categories are menu, packages, method (`#implementor`), examples (`#example`), pragma (`#pragma`), senders (`#sender`), class references (`#reference`) but also playground code snippets (using `#playground`). You can just type the beginning of the category to identify it i.e., `#ref Point` will give all the reference to the class Point.

**Spotter** can be used even to browse through the OS file system, and has a history category where previous searches are stored for quickly going back to popular searches.

## Navigating results

In addition we can use **Spotter** to navigate to our search results similarly to how we use System Browser. Spotter categorizes its search results: for example, classes are under `Classes` category, methods under the `Implementors` category, help topics under `Help Topics` category, etc.

Clicking on the right arrow will take us to our selection and create a tab on top
<figure><img src="image_18.png" /><figcaption>**Figure 2.13:** Looking for implementors matching `printString`</figcaption></figure>

that we can click to go back to where we were. Depending on what we click on, we step into our selection and are exposed to more categories.

For example, if our selection is the `Point` class, we will dive inside a group of categories made for instance methods, class methods, super instance methods etc.

The interface is fully controllable through the keyboard. The user can move with Up/Down arrows between items or `Cmd-Shift-Up/Cmd-Shift-Down` arrows (note that on Windows and Linux `Cmd` key is the `Alt` key) through categories. At the same time, the search field has the focus, so the user can switch seamlessly between selecting items and refining the search. Pressing `Enter` on a selection opens the System Browser on that specific selected search result.

## Using 'Find class' in System Browser

In the SystemBrowser you can also search for a class via its name. For example, suppose that you are looking for some unknown class that represents dates and times.

In the System Browser, click anywhere in the package pane or the class pane,
and launch the Class Search window by typing `CMD-f CMD-c`, or selecting `Find class (f, c)` from the right-click context menu. Type `time` in the dialog box and click `OK` (or press `Enter`).

A list of classes is displayed, whose names contain the substring `time`. Choose one (say, `Time`), and the browser will show it, along with a class comment that suggests other classes that might be useful. If you want to browse one of the others, select its name (in any text pane), and type `CMD-b`.

Note that if you type the complete (and correctly capitalized) name of a class in the find dialog, the browser will go directly to that class without showing you the list of options.

## Using the Finder

You can also open the Finder that is available from the `World > Tools...` menu, and type part of the name of the class and change the Selectors to Classes in the right combo box. It is less efficient than using **Spotter** or the SystemBrowser as explained above. The Finder is more useful for other types of code searches such as find methods based on examples, as we will show later.

## 2.12 Finding methods

Sometimes you can guess the name of a method, or at least part of the name of a method, more easily than the name of a class. For example, if you are interested in the current time, you might expect that there would be a method called `now`, or containing `now` as a substring. But where might it be? **Spotter** and **Finder** can help you.

### Spotter

With **Spotter** you can also find methods. Either by getting a class and navigating or using category such as:

* `#implementor` a method name will display all the methods that are implemented and have the same name. For example you will get all the `do:` methods.

* `#selector` a method name will display all the selectors that matches this name

### With Finder

Select `World Menu > Tools > Finder`. Type `now` in the top left search box, click `Search` (or just press the `Enter` key). You should see a list of results similar to the one in Figure 2.14.
<figure><img src="image_19.png" /><figcaption>**Figure 2.14:** The Finder showing all classes defining a method named now.</figcaption></figure>

The Finder will display a list of all the method names that contain the substring "now". To scroll to now itself, move the cursor to the list and type "n"; this type-ahead trick works in all scrolling windows. Expanding the "now" item shows you the classes that implement a method with this name. Selecting any one of them will display the source code for the implementation in the code pane on the bottom.

## Finding methods using examples

At other times, you may have a good idea that a method exists, but will have no idea what it might be called. The Finder can still help! For example, suppose that you would like to find a method that turns a string into upper case (for example, transforming 'eureka' into 'EUREKA'). We can give the inputs and expected output of a method and the Finder will try to find it for you.

The Finder has a really powerful functionality: you can give the receiver, arguments and expected result and the finder tries to find the corresponding message.

## Trying Finder

In the Finder, select the **Examples** mode using the second combo-box (the one that shows ** Selectors** by default).
Type 'eureka' . 'EUREKA' into the search box and press the Enter key.

The **Finder** will then suggest a method that does what you were looking for, as well as display a list of classes that implement methods with the same name. In this case, it determined that the `asUppercase` method is the one that performed the operation that fit your example.

Click on the 'eureka' asUppercase `--> 'EUREKA'` expression, to show the list of classes that implement that method.

An asterisk at the beginning of a line in the list of classes indicates that this method is the one that was actually used to obtain the requested result. So, the asterisk in front of `String` lets us know that the method `asUppercase` defined in the class `String` was executed and returned the result we wanted. The classes that do not have an asterisk are just other implementors of `asUppercase`, which share the method name but were *not* used to return the wanted result. So the method `Character>>asUppercase` was not executed in our example, because 'eureka' is not a `Character` instance (but is instead a `String`).

You can also use the **Finder** to search for methods by arguments and results. For example, if you are looking for a method that will find the greatest common factor of two integers, you might try `25 . 35 . 5` as an example. You can also give the method finder multiple examples to narrow the search space; the help text in the bottom pane explains how.

## 2.13 Defining a new method

The advent of Test Driven Development (TDD) has changed the way we write code. The idea behind TDD is that we write a test that defines the desired behaviour of our code before we write the code itself. Only then do we write the code that satisfies the test.

Suppose that our assignment is to write a method that "says something loudly and with emphasis". What exactly could that mean? What would be a good name for such a method? How can we make sure that programmers who may have to maintain our method in the future have an unambiguous description of what it should do? We can answer all of these questions by giving an example.

Our goal is to define a new method named `shout` in the class `String`. The idea is that this message should turn a string into its uppercase version as shown in the example below:

```javascript
'No panic' shout
>>> 'NO PANIC!'
```

However, before creating the `shout` method itself, we must first create a test method! In the next section, we can use the "No Panic" example to create our test method.
<figure><img src="image_20.png" /><figcaption>**Figure 2.15:** Defining a test method in the class `StringTest`.</figcaption></figure>

## Defining a new test method

How do we create a new method in Pharo? First, we have to decide which class the method should belong to. In this case, the `shout` method that we are testing will go in class `String`, so the corresponding test will, by convention, go in a class called `StringTest`.

First, open a browser on the class `StringTest`, and select an appropriate protocol for our method, in this case `'tests - converting'`. The highlighted text in the bottom pane is a template that reminds you what a Pharo method looks like. Delete this template code (remember, you can either click on the beginning or the end of the text, or press `CMD-a`, to "Select All"), and start typing your method. We can turn our "No Panic" code example into the test method itself:

```ruby
testShout
    self assert: ('No panic' shout = 'NO PANIC!')
```

Once you have typed the text into the browser, notice that the corner is orange. This is a reminder that the pane contains unsaved changes. So, select `Accept (s)` by right clicking in the bottom pane, or just type `CMD-s`, to compile and save your method. You should see a situation similar to the one depicted in Figure 2.15.

If this is the first time you have accepted any code in your image, you will likely be prompted to enter your name. Since many people have contributed code to the image, it is important to keep track of everyone who creates or modifies methods. Simply enter your first and last names, without any spaces.

Because there is as yet no method called `shout`, the automatic code checker (Quality Assurance) in the lower browser pane will inform you, that the mes-
2.13 Defining a new method

<figure><img src="image_21.png" /><figcaption>Figure 2.16: Looking at the error in the debugger.</figcaption></figure>

sage shout is sent but not implemented. This can be quite useful if you have merely made a typing mistake, but in this case, we really do mean shout, since that is the method we are about to create. We confirm this by selecting the first option from the menu of choices.

Running your test method

Run your newly created test: open the Test Runner from the World Menu (or press on the circle icon in front of the method name this is faster and cooler).

In the Test Runner the leftmost two panes are a bit like the top panes in the System Browser. The left pane contains a list of packages, but it's restricted to those packages that contain test classes.

Select `CollectionsTests-Strings` package, and the pane to the right will show all of the test classes in it, which includes the class `StringTest`. Class names are already selected, so click Run Selected to run all these tests.

You should see the upper right pane turn red, which indicates that there was an error in running the tests. The list of tests that gave rise to errors is shown in the bottom right pane. As you can see, the method `StringTest>>test-Shout` is the culprit. (Note that `StringTest>>testShout` is the Pharo way of identifying the `testShout` method of the `StringTest` class.) If you click on that method in the bottom right pane, the erroneous test will run again, this time in such a way that you see the error happen: `MessageNotUnderstood: ByteString>>shout` (see Figure 2.16).
<figure><img src="image_22.png" /><figcaption>**Figure 2.17:** Pressing the Create button in the debugger prompts you to select in which class to create the new method.</figcaption></figure>

<figure><img src="image_23.png" /><figcaption>**Figure 2.18:** The automatically created shout method waiting for a real definition.</figcaption></figure>

The window that opens with the error message is the Pharo debugger. We will look at the debugger and how to use it in Chapter: The Pharo Environment.

## Implementing the tested method

The error is, of course, exactly what we expected: running the test generates an error because we haven't yet written a method that tells strings how to shout. Nevertheless, it's good practice to make sure that the test fails because this confirms that we have set up the testing machinery correctly and that the new test is actually being run. Once you have seen the error, you can Abandon the running test, which will close the debugger window.

## Coding in the debugger

Instead of pressing Abandon, you can define the missing method using the Create button right in the debugger. This will prompt you to select a class in
which to define the new method (see Figure 2.17), then prompt you to select a protocol for that method, and finally take you to a code editor window in the debugger, in which you can edit the code for this new method. Note that since the system cannot implement the method for you, it creates a generic method that is tagged as to be implemented (see Figure 2.18).

Now let's define the method that will make the test succeed! Right inside the debugger edit the shout method with this definition:

```python
shout
    ^ self asUppercase, '!'
```

The comma is the string concatenation operation, so the body of this method appends an exclamation mark to an upper-case version of whatever String object the shout message was sent to. The `^` tells Pharo that the expression that follows is the answer to be returned from the method, in this case the new concatenated string.

When you've finished implementing the method, do not forget to compile it using `CMD-s` and you can press `Proceed` and continue with the tests. Note that `Proceed` simply continues on running the test suite, and does not re-run the failed method.

**Does this method work?** Let's run the tests and see. Click on Run Selected again in the Test Runner, and this time you should see a green bar and text indicating that all of the tests ran with no failures and no errors. When you get to a green bar, it's a good idea to save your work by saving the image (World Menu > Save), and take a break. So, do that right now!

## 2.14 Chapter summary

This chapter has introduced you to the Pharo environment and shown you how to use some of the major tools, such as the System Browser, Spotter, the Finder, the Debugger, and the Test Runner. You have also seen a little of Pharo's syntax, even though you may not understand it all yet.

* A running Pharo system consists of a *virtual machine*, a *sources file*, and *image* and *changes files*. Only these last two change, as they record a snapshot of the running system.

* When you open a Pharo image, you will find yourself in exactly the same state (i.e., with exactly the same running objects) that you had when you last saved that image.

* You can click on the Pharo background to bring up the **World Menu** and launch various tools.

* A **Playground** is a tool for writing and evaluating snippets of code. You can also use it to store arbitrary text.
* You can use keyboard shortcuts on text in the playground, or any other tool, to evaluate code. The most important of these are **Do it** (CMD-d), **Print it** (CMD-p), **Inspect it** (CMD-i), and **Browse it** (CMD-b).

* The **System Browser** is the main tool for browsing Pharo code and for developing new code.

* The **Test runner** is a tool for running unit tests, and aids in Test Driven Development.

* The **Debugger** allows you to examine errors and exceptions (such as errors or failures encountered when running tests). You can even create new methods right in the debugger.
CHAPTER 3

A first application

In this chapter, we will develop a simple game: LightsOut (http://en.wikipedia.org/wiki/Lights_Out_(game)). Along the way we will show most of the tools that Pharo programmers use to construct and debug their programs, and show how programs are shared with other developers. We will see the browser, the object inspector, the debugger and the Monticello package browser.

In Pharo you can develop in a traditional way, by defining a class, then its instance variables, then its methods. However, in Pharo your development flow can be much more productive than that! You can define instance variables and methods on the fly. You can also code in the debugger using the exact context of currently executed objects. This chapter will sketch such alternate way and show you how you can be really productive.

<figure><img src="image_24.png" /><figcaption>**Figure 3.1:** The Lights Out game board</figcaption></figure>
<figure><img src="image_25.png" /><figcaption>**Figure 3.2:** Create a Package and class template</figcaption></figure>

## 3.1 The Lights Out game

To show you how to use Pharo's programming tools, we will build a simple game called **Lights Out**. The game board consists of a rectangular array of light yellow cells. When you click on one of the cells, the four surrounding cells turn blue. Click again, and they toggle back to light yellow. The object of the game is to turn blue as many cells as possible.

**Lights Out** is made up of two kinds of objects: the game board itself, and 100 individual cell objects. The Pharo code to implement the game will contain two classes: one for the game and one for the cells. We will now show you how to define these classes using the Pharo programming tools.

## 3.2 Creating a new Package

We have already seen the browser in Chapter : A Quick Tour of Pharo where we learned how to navigate to packages, classes and methods, and saw how to define new methods. Now we will see how to create packages and classes.

From the World menu, open a **System Browser**. Right-click on an existing package in the Package pane and select Add package... from the menu. Type the name of the new package (we use PBE-LightsOut) in the dialog box and click OK (or just press the return key). The new package is created, and positioned alphabetically in the list of packages (see Figure 3.2).

**Hints:** You can type PBE in the filter to get your package filtered out the other ones (See Figure 3.3).
### 3.3 Defining the class LOCell

<figure><img src="image_26.png" /><figcaption>Figure 3.3: Filtering our package to work more efficiently</figcaption></figure>

## 3.3 Defining the class LOCell

At this point there are, of course, no classes in the new package. However, the main editing pane displays a template to make it easy to create a new class (see Figure 3.3).

This template shows us a Pharo expression that sends a message to a class called `Object`, asking it to create a subclass called `NameOfSubClass`. The new class has no variables, and should belong to the category (package) `PBE-LightsOut`.

### Creating a new class

We simply edit the template to create the class that we really want. Modify the class creation template as follows:

* Replace `Object` with `SimpleSwitchMorph`.

* Replace `NameOfSubClass` with `LOCell`.

* Add `mouseAction` to the list of instance variables.

You should get the following class definition:

```ruby
SimpleSwitchMorph subclass: #LOCell
instanceVariableNames: 'mouseAction'
classVariableNames: ''
package: 'PBE-LightsOut'
```

This new definition consists of a Pharo expression that sends a message to the existing class `SimpleSwitchMorph`, asking it to create a subclass called `LOCell`. (Actually, since `LOCell` does not exist yet, we passed the symbol `#LOCell` as an argument, representing the name of the class to create.) We also tell it that instances of the new class should have a `mouseAction` instance variable, which
<figure><img src="image_27.png" /><figcaption>**Figure 3.4:** The newly-created class LOCell</figcaption></figure>

we will use to define what action the cell should take if the mouse should click on it.

At this point you still have not created anything. Note that the top right of the panel changed to orange. This means that there are unsaved changes. To actually send this subclass message, you must save (accept) the source code. Either right-click and select Accept, or use the shortcut CMD-S (for "Save"). The message will be sent to SimpleSwitchMorph, which will cause the new class to be compiled. You should get the situation depicted in Figure 3.4.

Once the class definition is accepted, the class is created and appears in the class pane of the browser (see Figure 3.4). The editing pane now shows the class definition. Below you get the Quality Assistant's feedback: It runs automatically quality rules on your code and reports them.

## About comments

Pharoers put a very high value on the readability of their code, but also good quality comments.

**Method comments.** People have the tendency to believe that it is not necessary to comment well written methods: it is plain wrong and encourages sloppiness. Of course, bad code should renamed and refactored. Obviously commenting trivial methods makes no sense. A comment should not be the code written in english but an explanation of what the method is doing, its
context, or the rationale behind its implementation. When reading a com-
ment, the reader should be comforted that his hypotheses are correct.

**Class comments.** For the class comment, the Pharo class comment template gives a good idea of a strong class comment. Read it! It is based on CRC for Class Responsibility Collaborators. So in a nutshell the comments state the responsibility of the class in a couple of sentences and how it collaborates with other classes to achieve this responsibilities. In addition we can state the API (main messages an object understands), give an example (usually in Pharo we define examples as class methods), and some details about internal representation or implementation rationale.

Select the comment button and define a class comment following this tem-
plate

**On categories vs. packages**

Historically, Pharo packages were implemented as "categories" (a group of classes). With the newer versions of Pharo, the term **category** is being deprecated, and replaced exclusively by **package**.

If you use an older version of Pharo or an old tutorial, the class template will
be as follow:

```
SimpleSwitchMorph subclass: #LOCell
instanceVariableNames: 'mouseAction'
classVariableNames: ''
category: 'PBE-LightsOut'
```

It is equivalent to the one we mentioned earlier. In this book we only use the
term **package**. The Pharo package is also what you will be using to version
your source code using the Monticello versioning tool.

3.4 Adding methods to a class

Now let's add some methods to our class. Select the protocol 'no messages'
in the protocol pane. You will see a template for method creation in the
editing pane. Select the template text, and replace it by the following (Do not
forget to compile it):

```
initialize
    super initialize.
    self label: ''.
    self borderWidth: 2.
    bounds := 0 @ 0 corner: 16 @ 16.
    offColor := Color paleYellow.
    onColor := Color paleBlue darker.
    self useSquareCorners.
```
<figure><img src="image_28.png" /><figcaption>**Figure 3.5:** The newly-created method `initialize`</figcaption></figure>

```python
self turnOff
```

Note that the characters `''` on line 3 are two separate single quotes with nothing between them, not a double quote! `''` denotes the empty string. Another way to create an empty string is `String new`. Do not forget to accept this method definition.

**Initialize methods.** Notice that the method is called `initialize`. The name is very significant! By convention, if a class defines a method named `initialize`, it is called right after the object is created. So, when we execute `LOCell new`, the message `initialize` is sent automatically to this newly created object. `initialize` methods are used to set up the state of objects, typically to set their instance variables; this is exactly what we are doing here.

**Invoking superclass initialization.** The first thing that this method does (line 2) is to execute the `initialize` method of its superclass, `SimpleSwitchMorph`. The idea here is that any inherited state will be properly initialized by the `initialize` method of the superclass. It is always a good idea to initialize inherited state by sending super `initialize` before doing anything else. We don't know exactly what `SimpleSwitchMorph's` `initialize` method will do (and we don't care), but it's a fair bet that it will set up some instance variables to hold reasonable default values. So we had better call it, or we risk starting in an unclean state.
The rest of the method sets up the state of this object. Sending `self label: ''`, for example, sets the label of this object to the empty string.

**About point and rectangle creation.** The expression `0@0 corner: 16@16` probably needs some explanation. `0@0` represents a Point object with x and y coordinates both set to 0. In fact, `0@0` sends the message `@` to the number 0 with argument 0. The effect will be that the number 0 will ask the Point class to create a new instance with coordinates `(0, 0)`. Now we send this newly created point the message `corner: 16@16`, which causes it to create a Rectangle with corners `0@0` and `16@16`. This newly created rectangle will be assigned to the `bounds` variable, inherited from the superclass.

Note that the origin of the Pharo screen is the top left, and the y coordinate increases downwards.

**About the rest.** The rest of the method should be self-explanatory. Part of the art of writing good Pharo code is to pick good method names so that the code can be read like a kind of pidgin English. You should be able to imagine the object talking to itself and saying "Self, use square corners!", "Self, turn off!".

Notice that there is a little green arrow next to your method (see Figure 3.5). This means the method exists in the superclass and is overridden in your class.

## 3.5 Inspecting an object

You can immediately test the effect of the code you have written by creating a new `LOCell` object and inspecting it: Open a `Playground`, type the expression `LOCell new`, and **Inspect** it (using the menu item with the same name).

The left-hand column of the inspector shows a list of instance variables and the value of the instance variable is shown in the right column (see Figure 3.6).

If you click on an instance variable the inspector will open a new pane with the detail of the instance variable (see Figure 3.7).

**Executing expressions.** The bottom pane of the inspector is a mini-playground. It's useful because in this playground the pseudo-variable `self` is bound to the object selected.

Go to that `Playground` at the bottom of the pane and type the text `self bounds: (200@200 corner: 250@250) Do it`. To refresh the values, click on the update button (the blue little circle) at the top right of the pane. The `bounds` variable should change in the inspector. Now type the text `self open-InWorld` in the mini-playground and **Do it**.
<figure><img src="image_29.png" /><figcaption>Figure 3.6: The inspector used to examine a LOCell object</figcaption></figure>

<figure><img src="image_30.png" /><figcaption>Figure 3.7: When we click on an instance variable, we inspect its value (another object)</figcaption></figure>
### 3.6 Defining the class LOGame

<figure><img src="image_31.png" /><figcaption>Figure 3.8: An LOCell open in world</figcaption></figure>

The cell should appear near the top left-hand corner of the screen (as shown in Figure 3.8) and exactly where its bounds say that it should appear. Meta-click on the cell to bring up the Morphic halo. Move the cell with the brown (next to top-right) handle and resize it with the yellow (bottom-right) handle. Notice how the bounds reported by the inspector also change. (You may have to click refresh to see the new bounds value.) Delete the cell by clicking on the x in the pink handle.

## 3.6 Defining the class LOGame

Now let's create the other class that we need for the game, which we will name LOGame.

### Class creation

Make the class definition template visible in the browser main window. Do this by clicking on the package name (or right-clicking on the Class pane and selecting Add Class). Edit the code so that it reads as follows, and Accept it.

```kotlin
BorderedMorph subclass: #LOGame
instanceVariableNames: ''
classVariableNames: ''
package: 'PBE-LightsOut'
```
<figure><img src="image_32.png" /><figcaption>**Figure 3.9:** Declaring `cells` as a new instance variable</figcaption></figure>

Here we subclass `BorderedMorph`. `Morph` is the superclass of all of the graphical shapes in Pharo, and (unsurprisingly) a `BorderedMorph` is a `Morph` with a border. We could also insert the names of the instance variables between the quotes on the second line, but for now, let's just leave that list empty.

## Initializing our game

Now let's define an `initialize` method for `LOGame`. Type the following into the browser as a method for `LOGame` and try to Accept it.

```ruby
initialize
  | sampleCell width height n |
  super initialize.
  n := self cellsPerSide.
  sampleCell := LOCell new.
  width := sampleCell width.
  height := sampleCell height.
  self bounds: (5 @ 5 extent: (width * n) @ (height * n) + (2 * self borderWidth)).
  cells := Matrix new: n tabulate: [ :i :j | self newCellAt: i at: j ]
```

Pharo will complain that it doesn't know the meaning of `cells` (see Figure 3.9). It will offer you a number of ways to fix this.

Choose **Declare new instance variable**, because we want `cells` to be an instance variable.

## Taking advantage of the debugger

At this stage if you open a `Playground`, type `LOGame new`, and **Do it**, Pharo will complain that it doesn't know the meaning of some of the terms (see Figure 3.10). It will tell you that it doesn't know of a message `cellsPerSide`, and will open a debugger. But `cellsPerSide` is not a mistake; it is just a method that we haven't yet defined. We will do so, shortly.

Now let us do it: type `LOGame new` and **Do it**. Do not close the debugger. Click on the button **Create** of the debugger, when prompted, select `LOGame`, the class which will contain the method, click on **ok**, then when prompted for
### 3.6 Defining the class LOGame

<figure><img src="image_33.png" /><figcaption>Figure 3.10: Pharo detecting an unknown selector</figcaption></figure>

a method protocol enter accessing. The debugger will create the method `cellsPerSide` on the fly and invoke it immediately. As there is no magic, the created method will simply raise an exception and the debugger will stop again (as shown in Figure 3.11) giving you the opportunity to define the behavior of the method.

Here you can write your method. This method could hardly be simpler: it answers the constant 10. One advantage of representing constants as methods is that if the program evolves so that the constant then depends on some other features, the method can be changed to calculate this value.

```
cellsPerSide
  "The number of cells along each side of the game"
  ^ 10
```

Define the method `cellsPerSide` in the debugger. Do not forget to compile the method definition by using `Accept`. You should obtain a situation as shown by Figure 3.12. If you press the button `Proceed` the program will continue its execution - here it will stop since we did not define the method `newCellAt:`. We could use the same process but for now we stop to explain a bit what we did so far. Close the debugger, and look at the class definition once again (which you can do by clicking on `LOGame` on the second pane of the System Browser), you will see that the browser has modified it to include the instance variable `cells`.
<figure><img src="image_34.png" /><figcaption>**Figure 3.11:** The system created a new method with a body to be defined.</figcaption></figure>

## Studying the initialize method

Let us now study the method initialize.

1 initialize

2 | sampleCell width height n |

3 super initialize.

4 n := self cellsPerSide.

5 sampleCell := LOCell new.

6 width := sampleCell width.

7 height := sampleCell height.

8 self bounds: (5 @ 5 extent: (width * n) @ (height * n) + (2 * self borderWidth)).

9 cells := Matrix new: n tabulate: [ :i :j | self newCellAt: i at: j ]

* At line 2, the expression `| sampleCell width height n |` declares 4 temporary variables. They are called temporary variables because their scope and lifetime are limited to this method. Temporary variables with explanatory names are helpful in making code more readable. Lines 4-7 set the value of these variables.

* How big should our game board be? Big enough to hold some integral
### 3.6 Defining the class `LOGame`

<figure><img src="image_35.png" /><figcaption>Figure 3.12: Defining `cellsPerSide` in the debugger</figcaption></figure>

number of cells, and big enough to draw a border around them. How many cells is the right number? 5? 10? 100? We don't know yet, and if we did, we would probably change our minds later. So we delegate the responsibility for knowing that number to another method, which we name `cellsPerSide`, and which we will write in a minute or two. Don't be put off by this: it is actually good practice to code by referring to other methods that we haven't yet defined. Why? Well, it wasn't until we started writing the `initialize` method that we realized that we needed it. And at that point, we can give it a meaningful name, and move on, without interrupting our flow.

* The fourth line uses this method, `n := self cellsPerSide`. sends the message `cellsPerSide` to `self`, i.e., to this very object. The response, which will be the number of cells per side of the game board, is assigned to `n`.

* The next three lines create a new `LOCell` object, and assign its width and height to the appropriate temporary variables.

* Line 8 sets the bounds of the new object. Without worrying too much about the details just yet, believe us that the expression in parentheses
creates a square with its origin (i.e., its top-left corner) at the point (5,5) and its bottom-right corner far enough away to allow space for the right number of cells.

* The last line sets the `LOGame` object's instance variable `cells` to a newly created `Matrix` with the right number of rows and columns. We do this by sending the message `new: tabulate:` to the `Matrix` class (classes are objects too, so we can send them messages). We know that `new: tabulate:` takes two arguments because it has two colons (`:`) in its name. The arguments go right after the colons. If you are used to languages that put all of the arguments together inside parentheses, this may seem weird at first. Don't panic, it's only syntax! It turns out to be a very good syntax because the name of the method can be used to explain the roles of the arguments. For example, it is pretty clear that `Matrix rows: 5` columns: 2 has 5 rows and 2 columns, and not 2 rows and 5 columns.

* `Matrix new: n tabulate: [ :i :j | self newCellAt: i at: j ]` creates a new $n \times n$ matrix and initializes its elements. The initial value of each element will depend on its coordinates. The $(i,j)^{th}$ element will be initialized to the result of evaluating `self newCellAt: i at: j`.

## 3.7 Organizing methods into protocols

Before we define any more methods, let's take a quick look at the third pane at the top of the browser. In the same way that the first pane of the browser lets us categorize classes into packages, the protocol pane lets us categorize methods so that we are not overwhelmed by a very long list of method names in the method pane. These groups of methods are called "protocols".

The browser also offers us the `--all--` virtual protocol, which, you will not be surprised to learn, contains all of the methods in the class.

If you have followed along with this example, the protocol pane may well contain the protocol as yet *unclassified*. Right-click in the protocol pane and select *categorize all uncategorized* to fix this, and move the *initialize method* to a new protocol called *initialization*.

How does the **System Browser** know that this is the right protocol? Well, in general Pharo can't know exactly, but in this case there is also an *initialize* method in the superclass, and it assumes that our *initialize* method should go in the same protocol as the one that it overrides.

**A typographic convention.** Pharoers frequently use the notation `Class >> method` to identify the class to which a method belongs. For example, the `cellsPerSide` method in class `LOGame` would be referred to as `LOGame >> cellsPerSide`. Just keep in mind that this is not Pharo syntax exactly, but merely a convenient notation to indicate "the instance method `cellsPerSide`
which belongs to the class `LOGame"`. (Incidentally, the corresponding notation for a class-side method would be `LOGame class >> someClassSideMethod`.)

From now on, when we show a method in this book, we will write the name of the method in this form. Of course, when you actually type the code into the browser, you don't have to type the class name or the `>>`; instead, you just make sure that the appropriate class is selected in the class pane.

## 3.8 Finishing the game

Now let's define the other method that are used by `LOGame >> initialize`. Let's define `LOGame >> newCellAt: at: in the initialization protocol.

```FLASH
LOGame >> newCellAt: i at: j
    "Create a cell for position (i,j) and add it to my on-screen
     representation at the appropriate screen position. Answer the
     new cell"

| c origin |
c := LOCell new.
origin := self innerBounds origin.
self addMorph: c.
c position: ((i - 1) * c width) @ ((j - 1) * c height) + origin.
c mouseAction: [ self toggleNeighboursOfCellAt: i at: j ]
```

**Formatting.** As you can see there are some tabulation and empty lines. In order to keep the same convention you can right-click on the method edit area and click on Format (or use `CMD-Shift-f` shortcut). This will format your method.

The method defined above created a new `LOCell`, initialized to position (i, j) in the Matrix of cells. The last line defines the new cell's `mouseAction` to be the block `[ self toggleNeighboursOfCellAt: i at: j ]`. In effect, this defines the callback behaviour to perform when the mouse is clicked. The corresponding method also needs to be defined.

```FLASH
LOGame >> toggleNeighboursOfCellAt: i at: j
  i > 1
    ifTrue: [ (cells at: i - 1 at: j) toggleState ].
  i < self cellsPerSide
    ifTrue: [ (cells at: i + 1 at: j) toggleState ].
  j > 1
    ifTrue: [ (cells at: i at: j - 1) toggleState ].
  j < self cellsPerSide
    ifTrue: [ (cells at: i at: j + 1) toggleState ]
```

The method ` toggleNeighboursOfCellAt: at: ` toggles the state of the four cells to the north, south, west and east of cell (i, j). The only complication is
<figure><img src="image_36.png" /><figcaption>**Figure 3.13:** Drag a method to a protocol</figcaption></figure>

that the board is finite, so we have to make sure that a neighboring cell exists
before we toggle its state.

Place this method in a new protocol called `game logic`. (Right-click in the protocol pane to add a new protocol.) To move (re-classify) the method, you can simply click on its name and drag it to the newly-created protocol (see Figure 3.13).

To complete the Lights Out game, we need to define two more methods in class `LOCell` this time to handle mouse events.

```aboARD
LOCell >> mouseAction: aBlock
    ^ mouseAction := aBlock
```

The method above does nothing more than set the cell's `mouseAction` variable to the argument, and then answers the new value. Any method that changes the value of an instance variable in this way is called a *setter method*; a method that answers the current value of an instance variable is called a *getter method*.

** Setter/Getter convention.** If you are used to getters and setters in other programming languages, you might expect these methods to be called `set MouseAction` and `get MouseAction`. The Pharo convention is different. A getter always has the same name as the variable it gets, and a setter is named similarly, but with a trailing `:`; hence `mouseAction` and `mouseAction:`. Collectively, setters and getters are called *accessor methods*, and by convention they should be placed in the accessing protocol. In Pharo, all instance variables are private to the object that owns them, so the only way for another object to read or write those variables is through accessor methods like this one. In fact, the instance variables can be accessed in subclasses too.
Go to the class `LOCell`, define `LOCell >> mouseAction:` and put it in the accessing protocol.

Finally, we need to define a method `mouseUp:`. This will be called automatically by the GUI framework if the mouse button is released while the cursor is over this cell on the screen. Add the method `LOCell >> mouseUp:` and then **Categorize automatically** the methods.

```python
LOCell >> mouseUp: anEvent
mouseAction value
```

What this method does is to send the message value to the object stored in the instance variable `mouseAction`. In `LOGame >> newCellAt: i at: j` we created the *block* `[self toggleNeighboursOfCellAt: i at: j]` which is toggling all the neighbours of a cell and we assigned this block to the `mouseAction` of the cell. Therefore sending the value message causes this block to be evaluated, and consequently the state of the cells will toggle.

## 3.9 Let's try our code

That's it: the *Lights Out* game is complete! If you have followed all of the steps, you should be able to play the game, consisting of just 2 classes and 7 methods. In a *Playground*, type `LOGame new openInWorld` and **Do it**.

The game will open, and you should be able to click on the cells and see how it works. Well, so much for theory... When you click on a cell, a debugger will appear. In the upper part of the debugger window you can see the execution stack, showing all the active methods. Selecting any one of them will show, in the middle pane, the *Smalltalk* code being executed in that method, with the part that triggered the error highlighted.

Click on the line labeled `LOGame >> toggleNeighboursOfCellAt: at:` (near the top). The debugger will show you the execution context within this method where the error occurred (see Figure 3.14).

At the bottom of the debugger is a variable zone. You can inspect the object that is the receiver of the message that caused the selected method to execute, so you can look here to see the values of the instance variables. You can also see the values of the method arguments.

Using the debugger, you can execute code step by step, inspect objects in parameters and local variables, evaluate code just as you can in a *playground*, and, most surprisingly to those used to other debuggers, change the code while it is being debugged! Some Pharoers program in the debugger almost all the time, rather than in the browser. The advantage of this is that you see the method that you are writing as it will be executed, with real parameters in the actual execution context.

In this case we can see in the first line of the top panel that the ` toggleState` message has been sent to an instance of `LOGame`, while it should clearly have
<figure><img src="image_37.png" /><figcaption>**Figure 3.14:** The debugger, with the method ` toggleNeighboursOfCellAt: i at: j ` selected</figcaption></figure>

been an instance of LOCell. The problem is most likely with the initialization of the cells matrix. Browsing the code of LOGame >> initialize shows that cells is filled with the return values of newCellAt: at:, but when we look at that method, we see that there is no return statement there! By default, a method returns self, which in the case of newCellAt: at: is indeed an instance of LOGame. The syntax to return a value from a method in Pharo is ^.

Close the debugger window. Add the expression ^ c to the end of the method
LOGame >> newCellAt: at: so that it returns c.

```log
LOGame >> newCellAt: i at: j
    "Create a cell for position (i,j) and add it to my on-screen
     representation at the appropriate screen position. Answer the
     new cell"

| c origin |
c := LOCell new.
origin := self innerBounds origin.
self addMorph: c.
c position: ((i - 1) * c width) @ ((j - 1) * c height) + origin.
c mouseAction: [ self toggleNeighboursOfCellAt: i at: j ].
^ c
```

Often, you can fix the code directly in the debugger window and click Proceed
to continue running the application. In our case, because the bug was in the initialization of an object, rather than in the method that failed, the easiest thing to do is to close the debugger window, destroy the running instance of the game (with the halo CMD-Alt-Shift and click), and create a new one.

Execute `LOGame new openInWorld` again because if you use the old game instance it will still contain the block with the old logic.

Now the game should work properly... or nearly so. If we happen to move the mouse between clicking and releasing, then the cell the mouse is over will also be toggled. This turns out to be behavior that we inherit from `SimpleSwitch-Morph`. We can fix this simply by overriding `mouseMove:` to do nothing:

```pharo
[LOCell >> mouseMove: anEvent
```

Finally we are done!

**About the debugger.** By default when an error occurs in Pharo, the system displays a debugger. However, we can fully control this behavior. For example we can write the error in a file. We can even serialize the execution stack in a file, zip and reopen it in another image. Now when we are in development mode the debugger is available to let us go as fast as possible. In production system, developers often control the debugger to hide their mistakes from their clients.

## 3.10 Saving and sharing Pharo code

Now that you have **Lights Out** working, you probably want to save it some- where so that you can archive it and share it with your friends. Of course, you can save your whole Pharo image, and show off your first program by running it, but your friends probably have their own code in their images, and don't want to give that up to use your image. What you need is a way of getting source code out of your Pharo image so that other programmers can bring it into theirs.

> Note We'll be discussing the various ways to save and share code in a future chapter, Chapter : Sharing Code and Source Control. For now, here is an overview of some of the available methods.

### Saving plain code

The simplest way of doing this is by "filing out" the code. The right-click menu in the Package pane will give you the option to File Out the whole of package `PBE-LightsOut`. The resulting file is more or less human readable, but is really intended for computers, not humans. You can email this file to your friends, and they can file it into their own Pharo images using the file list browser.
<figure><img src="image_38.png" /><figcaption>Figure 3.15: File Out our PBE-LightsOut</figcaption></figure>

<figure><img src="image_39.png" /><figcaption>Figure 3.16: Import your code with the file browser</figcaption></figure>

Right-click on the PBE-LightsOut package and file out the contents (see Figure 3.15). You should now find a file named PBE-LightsOut.st in the same folder on disk where your image is saved. Have a look at this file with a text editor.

Open a fresh Pharo image and use the File Browser tool (Tools --> File Browser) to file in the PBE-LightsOut.st fileout (see Figure 3.16) and fileIn. Verify that the game now works in the new image.

## Monticello packages

Although fileouts are a convenient way of making a snapshot of the code you have written, they are definitely "old school". Just as most open-source projects find it much more convenient to maintain their code in a repository using SVN or Git, so Pharo programmers find it more convenient to manage their code using Monticello packages. These packages are represented as files
<figure><img src="image_40.png" /><figcaption>**Figure 3.17:** Monticello browser. The package PBE-LightsOut is not save yet</figcaption></figure>

with names ending in `.mcz`. They are actually zip-compressed bundles that contain the complete code of your package.

Using the Monticello package browser, you can save packages to repositories on various types of server, including FTP and HTTP servers. You can also just write the packages to a repository in a local file system directory. A copy of your package is also always cached on your local disk in the package-cache folder. Monticello lets you save multiple versions of your program, merge versions, go back to an old version, and browse the differences between versions. In fact, Monticello is a distributed revision control system. This means it allows developers to save their work on different places, not on a single repository as it is the case with CVS or Subversion.

You can also send a `.mcz` file by email. The recipient will have to place it in her package-cache folder; she will then be able to use Monticello to browse and load it.

## Monticello Browser

Open the Monticello browser from the World menu (see Figure 3.17).

In the right-hand pane of the browser is a list of Monticello repositories, which will include all of the repositories from which code has been loaded into the image that you are using. The top list item is a local directory called the package-cache. It caches copies of the packages that you have loaded or published over the network. This local cache is really handy because it lets you keep your own local history. It also allows you to work in places where you do not have internet access, or where access is slow enough that you do not want to save to a remote repository very frequently.
## Saving and loading code with Monticello

On the left-hand side of the Monticello browser is a list of packages that have a version loaded into the image. Packages that have been modified since they were loaded are marked with an asterisk. (These are sometimes referred to as dirty packages.) If you select a package, the list of repositories is restricted to just those repositories that contain a copy of the selected package.

Add the `PBE-LightsOut` package to your Monticello browser using the `+ Package` button and type `PBE-LightsOut`.

## SmalltalkHub: a Github for Pharo

We think that the best way to save your code and share it is to create an account for your project in SmalltalkHub. SmalltalkHub is like GitHub: it is a web front-end to a HTTP Monticello server that lets you manage your projects. There is a public server at http://www.smalltalkhub.com/.

To be able to use SmalltalkHub you will need an account. Open the site in your browser. Then, click on the **Join** link and follow the instructions to create a new account. Finally, **login** to your account. Click on the `+ New project` to create a new project. Fill in the information requested and click **Register project** button. You will be sent to your profile page, on the right side you will see the list of your projects and projects you watch by other coders. Click on the project you just created.

Under **Monticello registration** title label you will see a box containing a smalltalk message similar to

```
MCHttpRepository
  location: 'http://www.smalltalkhub.com/mc/UserName/ProjectName/main'
  user: 'YourName'
  password: 'Optional_Password'
```

Copy the contents and go back to Pharo. Once your project has been created on SmalltalkHub, you have to tell your Pharo system to use it. With the `PBE-LightsOut` package selected, click the `+Repository` button in the Monticello browser. You will see a list of the different Repository types that are available. To add a SmalltalkHub repository select `smalltalkhub.com`. You will be presented with a dialog in which you can provide the necessary information about the server. You should paste the code snippet you have copied from SmalltalkHub (see Figure 3.18). This message tells Monticello where to find your project online. You can also provide your user name and password. If you do not, then Pharo will ask for them each time you try to save into your online repository at SmalltalkHub.

Once you have accepted, your new repository should be listed on the right-hand side of the Monticello browser. Click on the **Save** button to save a first version of your Lights Out game on SmalltalkHub. Don't forget to put a comment
3.10 Saving and sharing Pharo code

<figure><img src="image_41.png" /><figcaption>Figure 3.18: Create your first repository on SmalltalkHub</figcaption></figure>

<figure><img src="image_42.png" /><figcaption>Figure 3.19: Do your first commit</figcaption></figure>

ment so that you, or others, will have an idea of what your commit contains
(see Figure 3.19).

To load a package into your image, open Monticello, select the repository where the package is located and click open button. It will open a new window with two columns, left one is the Package to be loaded, the right one is the version of the package to be loaded. Select the Package and the version you want to load and click the load button.

Open the PBE-LightsOut repository you have just saved. You should see the package you just saved.
Monticello has many more capabilities, which will be discussed in depth in
Chapter : Sharing Code and Source Control.

**About Git.** If you are already familiar with Git and Github there are several solutions to manage your projects with Git. This blog posts provides a summary: http://blog.yuriy.tymch.uk/2015/07/pharo-and-github-versioning-revision-2.html#! There is a chapter in preparation on about how to use Git with Pharo. Request it on the Pharo mailing-list.

3.11 Chapter summary

In this chapter you have seen how to create packages, classes and methods. In addition, you have learned how to use the System browser, the inspector, the debugger and the Monticello browser.

* Packages are groups of related classes.

• A new class is created by sending a message to its superclass.

* Protocols are groups of related methods inside a class.

* A new method is created or modified by editing its definition in the browser and then accepting the changes.

* The inspector offers a simple, general-purpose GUI for inspecting and interacting with arbitrary objects.

* The browser detects usage of undeclared variables, and offers possible corrections.

* The initialize method is automatically executed after an object is created in Pharo. You can put any initialization code there.

* The debugger provides a high-level GUI to inspect and modify the state of a running program.

* You can share source code by filing out a package, class or method.

* A better way to share code is to use Monticello to manage an external repository, for example defined as a SmalltalkHub project.
Syntax in a nutshell

Pharo adopts a syntax very close to that of its ancestor, Smalltalk. The syntax is designed so that program text can be read aloud as though it were a kind of pidgin English. The following method of the class Week shows an example of the syntax. It checks whether DayNames already contains the argument, i.e. if this argument represents a correct day name. If this is the case, it will assign it to the variable StartDay.

```
startDay: aSymbol

(DayNames includes: aSymbol)
    ifTrue: [ StartDay := aSymbol ]
    ifFalse: [ self error: aSymbol, ' is not a recognised day name' ]
```

Pharo's syntax is minimal. Essentially there is syntax only for sending messages (i.e. expressions). Expressions are built up from a very small number of primitive elements (message sends, assignments, closures, returns...). There are only 6 keywords, and there is no syntax for control structures or declaring new classes. Instead, nearly everything is achieved by sending messages to objects. For instance, instead of an if-then-else control structure, conditionals are expressed as messages (such as ifTrue:) sent to Boolean objects. New (sub-)classes are created by sending a message to their superclass.

4.1 Syntactic elements

Expressions are composed of the following building blocks:

1. The six reserved keywords, or pseudo-variables: self, super, nil, true, false, and thisContext
2. Constant expressions for literal objects including numbers, characters, strings, symbols and arrays

3. Variable declarations

4. Assignments

5. Block closures

6. Messages

We can see examples of the various syntactic elements in the Table below.

<table><thead><tr><td>Syntax</td><td>What it represents</td></tr></thead><tbody><tr><td>startPoint</td><td>a variable name</td></tr><tr><td>Transcript</td><td>a global variable name</td></tr><tr><td>self</td><td>pseudo-variable</td></tr><tr><td>1</td><td>decimal integer</td></tr><tr><td>2r101</td><td>binary integer</td></tr><tr><td>1.5</td><td>floating point number</td></tr><tr><td>2.4e7</td><td>exponential notation</td></tr><tr><td>$a</td><td>the character 'a'</td></tr><tr><td>'Hello'</td><td>the string 'Hello'</td></tr><tr><td>#Hello</td><td>the symbol #Hello</td></tr><tr><td>#(1 2 3)</td><td>a literal array</td></tr><tr><td>{ 1 . 2 . 1 + 2 }</td><td>a dynamic array</td></tr><tr><td>"a comment"</td><td>a comment</td></tr><tr><td>| x y |</td><td>declaration of variables x and y</td></tr><tr><td>x := 1</td><td>assign 1 to x</td></tr><tr><td>[:x | x + 2]</td><td>a block that evaluates to x + 2</td></tr><tr><td>&lt;primitive: 1&gt;</td><td>virtual machine primitive or annotation</td></tr><tr><td>3 factorial</td><td>unary message factorial</td></tr><tr><td>3 + 4</td><td>binary message +</td></tr><tr><td>2 raisedTo: 6 modulo: 10</td><td>keyword message raisedTo: modulo:</td></tr><tr><td>^ true</td><td>return the value true</td></tr><tr><td>x := 2 . x := x + x</td><td>expression separator (.)</td></tr><tr><td>Transcript show: 'hello'; cr</td><td>message cascade (;)</td></tr></tbody></table>

**Local variables.** `startPoint` is a variable name, or identifier. By convention, identifiers are composed of words in "camelCase" (i.e., each word except the first starting with an upper case letter). The first letter of an instance variable, method or block argument, or temporary variable must be lower case. This indicates to the reader that the variable has a private scope.

**Shared variables.** Identifiers that start with upper case letters are global variables, class variables, pool dictionaries or class names. `Transcript` is a global variable, an instance of the class `ThreadSafeTranscript`.

**The receiver.** `self` is a keyword that refers to the object inside which the current method is executing. We call it "the receiver" because this object
has received the message that caused the method to execute. `self` is called a "pseudo-variable" since we cannot assign to it.

**Integers.** In addition to ordinary decimal integers like 42, Pharo also provides a radix notation. `2r101` is 101 in radix 2 (i.e., binary), which is equal to decimal 5.

**Floating point numbers.** can be specified with their base-ten exponent: `2.4e7` is `2.4 × 10^7`.

**Characters.** A dollar sign introduces a literal character: `$a` is the literal for the character 'a'. Instances of non-printing characters can be obtained by sending appropriately named messages to the `Character` class, such as `Character space` and `Character tab`.

**Strings.** Single quotes `' '` are used to define a literal string. If you want a string with a single quote inside, just double the quote, as in `'G''day'`.

**Symbols.** Symbols are like Strings, in that they contain a sequence of characters. However, unlike a string, a literal symbol is guaranteed to be globally unique. There is only one `Symbol` object `#Hello` but there may be multiple `String` objects with the value `Hello`.

**Compile-time arrays.** are defined by `#( )`, surrounding space-separated literals. Everything within the parentheses must be a compile-time constant. For example, `#(27 (true false) abc)` is a literal array of three elements: the integer 27, the compile-time array containing the two booleans, and the symbol `abc`. (Note that this is the same as `#(27 #(true false) #abc).`)

**Run-time arrays.** Curly braces `{ }` define a (dynamic) array at run-time. Elements are expressions separated by periods. So `{ 1. 2. 1 + 2 }` defines an array with elements 1, 2, and the result of evaluating `1+2`.

**Comments.** are enclosed in double quotes `" "`. `"hello"` is a comment, not a string, and is ignored by the Pharo compiler. Comments may span multiple lines.

**Local variable definitions.** Vertical bars `| |` enclose the declaration of one or more local variables in a method (and also in a block).

**Assignment.** `:=` assigns an object to a variable.

**Blocks.** Square brackets `[ ]` define a block, also known as a block closure or a lexical closure, which is a first-class object representing a function. As we shall see, blocks may take arguments (`[:i | ...]`) and can have local variables.

**Primitives.** `< primitive: ... >` denotes an invocation of a virtual machine primitive. For example, `< primitive: 1 >` is the VM primitive for `Small-Integer`. Any code following the primitive is executed only if the primitive fails. The same syntax is also used for method annotations (pragmas).
**Unary messages.** These consist of a single word (like *factorial*) sent to a receiver (like 3). In 3 *factorial*, 3 is the receiver, and *factorial* is the message selector.

**Binary messages.** These are message with an argument and whose selector looks like mathematical expressions (for example: +) sent to a receiver, and taking a single argument. In 3 + 4, the receiver is 3, the message selector is +, and the argument is 4.

**Keyword messages.** They consist of multiple keywords (like *raisedTo: modulo:*) each ending with a colon and taking a single argument. In the expression 2 *raisedTo: 6 modulo: 10*, the message selector *raisedTo: modulo:* takes the two arguments 6 and 10, one following each colon. We send the message to the receiver 2.

**Method return.** ^ is used to *return* a value from a method.

**Sequences of statements.** A period or full-stop (.) is the statement separator. Putting a period between two expressions turns them into independent statements.

**Cascades.** Semicolons (;) can be used to send a cascade of messages to a single receiver. In *Transcript* show: 'hello'; cr we first send the keyword message show: 'hello' to the receiver *Transcript*, and then we send the unary message cr to the same receiver.

The classes *Number*, *Character*, *String* and *Boolean* are described in more detail in Chapter : Basic Classes.

## 4.2 Pseudo-variables

In Pharo, there are 6 reserved keywords, or pseudo-variables: *nil*, *true*, *false*, *self*, *super*, and *thisContext*. They are called pseudo-variables because they are predefined and cannot be assigned to. *true*, *false*, and *nil* are constants, while the values of *self*, *super*, and *thisContext* vary dynamically as code is executed.

* true and false are the unique instances of the Boolean classes *True* and *False*. See Chapter : Basic Classes for more details.

* *self* always refers to the receiver of the currently executing method.

* *super* also refers to the receiver of the current method, but when you send a message to *super*, the method-lookup changes so that it starts from the superclass of the class containing the method that uses *super*. For further details see Chapter : The Pharo Object Model.

* *nil* is the undefined object. It is the unique instance of the class *UndefinedObject*. Instance variables, class variables and local variables are initialized to *nil*.
* `thisContext` is a pseudo-variable that represents the top frame of the execution stack. `thisContext` is normally not of interest to most programmers, but it is essential for implementing development tools like the debugger, and it is also used to implement exception handling and continuations.

## 4.3 Message sends

There are three kinds of messages in Pharo. This distinction has been made to reduce the number of mandatory parentheses.

1. Unary messages take no argument. `1` factorial sends the message `factorial` to the object `1`.

2. Binary messages take exactly one argument. `1 + 2` sends the message `+` with argument `2` to the object `1`.

3. Keyword messages take an arbitrary number of arguments. `2 raisedTo: 6 modulo: 10` sends the message consisting of the message selector `raisedTo:modulo:` and the arguments `6` and `10` to the object `2`.

**Unary messages.** Unary message selectors consist of alphanumeric characters, and start with a lower case letter.

**Binary messages.** Binary message selectors consist of one or more characters from the following set:

`[ + - / \ * ~ < > = @ % | & ? , ]`

**Keyword message selectors.** Keyword message selectors consist of a series of alphanumeric keywords, where each keyword starts with a lower-case letter and ends with a colon.

**Message precedence.** Unary messages have the highest precedence, then binary messages, and finally keyword messages, so:

`[ 2 raisedTo: 1 + 3 factorial >>> 128 ]`

First we send `factorial` to `3`, then we send `+ 6` to `1`, and finally we send `raisedTo: 7` to `2`. Recall that we use the notation `>>>` to show the result of evaluating an expression.

Precedence aside, execution is strictly from left to right, so:

`[ 1 + 2 * 3 >>> 9 ]`

return `9` and not `7`. Parentheses must be used to alter the order of evaluation:
```
1 + (2 * 3)
>>> 7
```

**Periods and semi-colons.** Message sends may be composed with periods and semi-colons. A period separated sequence of expressions causes each expression in the series to be evaluated as a *statement*, one after the other.

```
Transcript cr.
Transcript show: 'hello world'.
Transcript cr
```

This will send `cr` to the Transcript object, then send it `show: 'hello world'`, and finally send it another `cr`.

When a series of messages is being sent to the *same* receiver, then this can be expressed more succinctly as a *cascade*. The receiver is specified just once, and the sequence of messages is separated by semi-colons:

```
Transcript
cr;
show: 'hello world';
cr
```

This has precisely the same effect as the previous example.

## 4.4 Method syntax

Whereas expressions may be evaluated anywhere in Pharo (for example, in a playground, in a debugger, or in a browser), methods are normally defined in a browser window, or in the debugger. Methods can also be filed in from an external medium, but this is not the usual way to program in Pharo.

Programs are developed one method at a time, in the context of a given class. A class is defined by sending a message to an existing class, asking it to create a subclass, so there is no special syntax required for defining classes.

Here is the method `lineCount` in the class `String`. The usual *convention* is to refer to methods as `ClassName» methodName`. Here the method is then `String»lineCount`. Note that `ClassName»methodName` is not part of the Pharo syntax just a convention used in books to clearly define a method.

```
String >> lineCount
  "Answer the number of lines represented by the receiver, where every
cr adds one line."

| cr count |
cr := Character cr.
count := 1 min: self size.
self do: [:c | c == cr ifTrue: [count := count + 1]].
^ count
```
Syntactically, a method consists of:

1. the method pattern, containing the name (i.e., `lineCount`) and any arguments (none in this example)

2. comments (these may occur anywhere, but the convention is to put one at the top that explains what the method does)

3. declarations of local variables (i.e., `cr` and `count`); and

4. any number of expressions separated by dots (here there are four)

The execution of any expression preceded by a `^` (a caret or upper arrow, which is Shift-6 for most keyboards) will cause the method to exit at that point, returning the value of that expression. A method that terminates without explicitly returning some expression will implicitly return `self`.

Arguments and local variables should always start with lower case letters. Names starting with upper-case letters are assumed to be global variables. Class names, like `Character`, for example, are simply global variables referring to the object representing that class.

## 4.5 Block syntax

Blocks (lexical closures) provide a mechanism to defer the execution of expressions. A block is essentially an anonymous function with a definition context. A block is executed by sending it the message `value`. The block answers the value of the last expression in its body, unless there is an explicit return (with `^`) in which case it returns the value of the returned expression.

```
[ 1 + 2 ] value
>>> 3

[ 3 = 3 ifTrue: [ ^ 33 ]. 44 ] value
>>> 33
```

Blocks may take parameters, each of which is declared with a leading colon. A vertical bar separates the parameter declaration(s) from the body of the block. To evaluate a block with one parameter, you must send it the message `value:` with one argument. A two-parameter block must be sent `value:value:`, and so on, up to 4 arguments.

```
[ :x | 1 + x ] value: 2
>>> 3
[ :x :y | x + y ] value: 1 value: 2
>>> 3
```

If you have a block with more than four parameters, you must use `valueWith-Arguments:` and pass the arguments in an array. (A block with a large number of parameters is often a sign of a design problem.)
Blocks may also declare local variables, which are surrounded by vertical bars, just like local variable declarations in a method. Locals are declared after any arguments:

```
[ :x :y |
| z |
z := x + y.
z ] value: 1 value: 2
>>> 3
```

Blocks are actually lexical closures, since they can refer to variables of the surrounding environment. The following block refers to the variable x of its enclosing environment:

```
| x |
x := 1.
[ :y | x + y ] value: 2
>>> 3
```

Blocks are instances of the class BlockClosure. This means that they are objects, so they can be assigned to variables and passed as arguments just like any other object.

## 4.6 Conditionals and loops in a nutshell

Pharo offers no special syntax for control constructs. Instead, these are typically expressed by sending messages to booleans, numbers and collections, with blocks as arguments.

### Some conditionals

Conditionals are expressed by sending one of the messages `ifTrue:`, `ifFalse:` or `ifTrue:ifFalse:` to the result of a boolean expression. See Chapter: Basic Classes, for more about booleans.

```
(17 * 13 > 220)
    ifTrue: [ 'bigger' ]
    ifFalse: [ 'smaller' ]
>>> 'bigger'
```

### Some loops

Loops are typically expressed by sending messages to blocks, integers or collections. Since the exit condition for a loop may be repeatedly evaluated, it should be a block rather than a boolean value. Here is an example of a very procedural loop:

```
| n := 1.
[ n < 1000 ] whileTrue: [ n := n*2 ].
```
```
n
>>> 1024
```

whileFalse: reverses the exit condition.

```
[ n := 1.
[ n > 1000 ] whileFalse: [ n := n*2 ].
n
>>> 1024
```

timesRepeat: offers a simple way to implement a fixed iteration:

```
[ n := 1.
10 timesRepeat: [ n := n*2 ].
n
>>> 1024
```

We can also send the message `to:do:` to a number which then acts as the initial value of a loop counter. The two arguments are the upper bound, and a block that takes the current value of the loop counter as its argument:

```
[ result := String new.
1 to: 10 do: [:n | result := result, n printString, ' '].
result
>>> '1 2 3 4 5 6 7 8 9 10 '
```

## High-order iterators

Collections comprise a large number of different classes, many of which support the same protocol. The most important messages for iterating over collections include `do:`, `collect:`, `select:`, `reject:`, `detect:` and `inject:into:`. These messages define high-level iterators that allow one to write very compact code.

An **Interval** is a collection that lets one iterate over a sequence of numbers from the starting point to the end. `1 to: 10` represents the interval from 1 to 10. Since it is a collection, we can send the message `do:` to it. The argument is a block that is evaluated for each element of the collection.

```
[ result := String new.
(1 to: 10) do: [:n | result := result, n printString, ' '].
result
>>> '1 2 3 4 5 6 7 8 9 10 '
```

`collect:` builds a new collection of the same size, transforming each element. (You can think of `collect:` as the Map in the MapReduce programming model).

```
[ (1 to:10) collect: [ :each | each * each ]
>>> #(1 4 9 16 25 36 49 64 81 100)
```

`select:` and `reject:` build new collections, each containing a subset of the elements satisfying (or not) the boolean block condition.
`detect:` returns the first element satisfying the condition. Don't forget that strings are also collections (of characters), so you can iterate over all the characters.

```javascript
'hello there' select: [ :char | char isVowel ]
>>> 'eoee'
'hello there' reject: [ :char | char isVowel ]
>>> 'hll thr'
'hello there' detect: [ :char | char isVowel ]
>>> $e
```

Finally, you should be aware that collections also support a functional-style fold operator in the `inject:into:` method. You can also think of it as the Reduce in the MapReduce programming model. This lets you generate a cumulative result using an expression that starts with a seed value and injects each element of the collection. Sums and products are typical examples.

```javascript
(1 to: 10) inject: 0 into: [ :sum :each | sum + each]
>>> 55
```

This is equivalent to `0+1+2+3+4+5+6+7+8+9+10`.

More about collections can be found in Chapter: Collections.

## 4.7 Primitives and pragmas

In Pharo everything is an object, and everything happens by sending messages. Nevertheless, at certain points we hit rock bottom. Certain objects can only get work done by invoking virtual machine primitives.

For example, the following are all implemented as primitives: memory allocation (new, new:), bit manipulation (bitAnd:, bitOr:, bitShift:), pointer and integer arithmetic (+, -, <, >, *, /, =, ==...), and array access (at:, at:put:).

Primitives are invoked with the syntax `<primitive: aNumber>`. A method that invokes such a primitive may also include Pharo code, which will be executed only if the primitive fails.

Here we see the code for `SmallInteger>>+`. If the primitive fails, the expression `super + aNumber` will be executed and returned.

```javascript
+ aNumber
  "Primitive. Add the receiver to the argument and answer with the
   result
  if it is a SmallInteger. Fail if the argument or the result is not a
  SmallInteger Essential No Lookup. See Object documentation
   whatIsAPrimitive."

<primitive: 1>
^ super + aNumber
```
In Pharo, the angle bracket syntax is also used for method annotations called pragmas.

4.8 Chapter summary

* Pharo has only six reserved identifiers (also called pseudo-variables): true, false, nil, self, super, and thisContext.

* There are five kinds of literal objects: numbers (5, 2.5, 1.9e15, 2r111), characters ($a), strings ('hello'), symbols (#hello), and arrays (#('hello' #hi) or { 1 . 2 . 1 + 2 })

* Strings are delimited by single quotes, comments by double quotes. To get a quote inside a string, double it.

* Unlike strings, symbols are guaranteed to be globally unique.

* Use #(...) to define a literal array. Use {...} to define a dynamic array. Note that #(1+2) size >>> 3, but {1+2} size >>> 1

* There are three kinds of messages: unary (e.g., 1 asString, Array new), binary (e.g., 3 + 4, 'hi', ' there'), and keyword (e.g., 'hi' at: 2 put: $o)

* A cascaded message send is a sequence of messages sent to the same target, separated by semi-colons: OrderedCollection new add: #calvin; add: #hobbes; size >>> 2

* Local variables are declared with vertical bars. Use := for assignment.
  |x| x := 1

* Expressions consist of message sends, cascades and assignments, evaluated left to right (and optionally grouped with parentheses). Statements are expressions separated by periods.

* Block closures are expressions enclosed in square brackets. Blocks may take arguments and can contain temporary variables. The expressions in the block are not evaluated until you send the block a value message with the correct number of arguments. [ :x | x + 2 ] value: 4

* There is no dedicated syntax for control constructs, just messages that conditionally evaluate blocks.
<figure><img src="image_43.png" /></figure>
CHAPTER 5

Understanding message syntax

Although Pharo's message syntax is simple, it is unconventional and can take some time getting used to. This chapter offers some guidance to help you get acclimatized to this special syntax for sending messages. If you already feel comfortable with the syntax, you may choose to skip this chapter, or come back to it later.

5.1 Identifying messages

In Pharo, except for the syntactic elements listed in Chapter : Syntax in a Nutshell (:= ^ . ; # () {} [ : | ] <>), everything is a message send. There is no operators, just messages sent to objects. Therefore you can define a message named + in your class but there is also no precedence because Pharo always takes the simplest form of definition.

The order in which messages are sent is determined by the type of message. There are just three types of messages: **unary**, **binary**, and **keyword messages**. Pharo distinguishes such three types of messages to minimize the number of parentheses. Unary messages are always sent first, then binary messages and finally keyword ones. As in most languages, parentheses can be used to change the order of execution. These rules make Pharo code as easy to read as possible. And most of the time you do not have to think about the rules.

**Message structure**

As most computation in Pharo is done by message passing, correctly identifying messages is key to avoiding future mistakes. The following terminology
<figure><img src="image_44.png" /></figure>

**Figure 5.1:** Two message sends composed of a receiver, a method selector, and a set of arguments.

<figure><img src="image_45.png" /></figure>

**Figure 5.2:** *aMorph color: Color yellow* is composed of two message sends: *Color yellow* and *aMorph color: Color yellow*.

will help us:

* A message is composed of the **message selector** and the optional message arguments.

* A message is sent to a **receiver**.

* The combination of a message and its **receiver** is called a *message send* as shown in Figure 5.1.

A message is always sent to a receiver, which can be a single literal, a block or a variable or the result of evaluating another message.

To help you identify the receiver of a message, we will underline it for you. We will also surround each message send with an ellipse, and number the message sends starting from the first one to help you see the send order in Figure 5.2.

Figure 5.2 represents two message sends, *Color yellow* and *aMorph color: Color yellow*, hence there are two ellipses. The message send *Color yellow* is executed first, so its ellipse is numbered 1. There are two receivers: 1) *aMorph* which receives the message *color: ...* and 2) *Color* which receives the message *yellow*. Both receivers are underlined.
## 5.2 Three types of messages

A receiver can be the first element of a message, such as `100` in the message send `100 + 200` or `Color yellow`. However, a receiver can also be the result of other messages. For example in the message send `Pen new go: 100`, the receiver of the message `go: 100` is the object returned by the message send `Pen new`. In all the cases, a message is sent to an object called the *receiver* which may be the result of another message send.

<table><thead><tr><td>Message send</td><td>Message type</td><td>Action</td></tr></thead><tbody><tr><td>Color yellow</td><td>unary</td><td>Creates a color</td></tr><tr><td>aPen go: 100</td><td>keyword</td><td>Forwards pen 100 pixels</td></tr><tr><td>100 + 20</td><td>binary</td><td>100 receives the message +</td></tr><tr><td>Browser open</td><td>unary</td><td>Opens a new browser</td></tr><tr><td>Pen new go: 100</td><td>un. and keyw.</td><td>Creates and moves pen 100 px</td></tr><tr><td>aPen go: 100 + 20</td><td>keyw. and bin.</td><td>Pen moves forward 120 px</td></tr></tbody></table>

The table shows several characteristics of message sends.

* You should note that not all message sends have arguments. Unary messages like `open` do not have arguments. Single keyword and binary messages like `go: 100` and `+ 20` each have one argument.

* There are also simple messages and composed ones. `Color yellow` and `100 + 20` are simple: a message is sent to an object, while the message send `aPen go: 100 + 20` is composed of two messages: `+ 20` is sent to `100` and `go:` is sent to `aPen` with the argument being the result of the first message.

* A receiver can be an expression (such as an assignment, a message send or a literal) which returns an object. In `Pen new go: 100`, the message `go: 100` is sent to the object that results from the execution of the message send `Pen new`.

## 5.2 Three types of messages

Pharo distinguishes between three kinds of messages to reduce mandatory parentheses. A few simple rules based on the such different message determine the order in which the messages are sent.

There are three different types of messages:

* Unary messages are messages that are sent to an object without any other information. For example, in `3 factorial`, `factorial` is a unary message.

* Binary messages are messages consisting of operators (often arithmetic). They are binary because they always involve only two objects: the receiver and the argument object. For example in `10 + 20`, `+` is a binary message sent to the receiver `10` with argument `20`.
* Keyword messages are messages consisting of one or more keywords, each ending with a colon (:) and taking an argument. For example in `anArray at: 1 put: 10`, the keyword `at:` takes the argument 1 and the keyword `put:` takes the argument 10.

## Unary messages

Unary messages are messages that do not require any argument. They follow the syntactic template: `receiver messageName`. The selector is simply made up of a succession of characters not containing `:` (e.g., `factorial`, `open`, `class`).

```
[ 89 sin
>>> 0.860069405812453

[ 3 sqrt
>>> 1.732050807568877

[ Float pi
>>> 3.141592653589793

['blop' size
>>> 4

[ true not
>>> false

[ Object class
>>> Object class "The class of Object is Object class (BANG)"
```

> **Important** Unary messages are messages that do not require any argument. They follow the syntactic template: `receiver selector`.

## Binary messages

Binary messages are messages that require exactly one argument and whose selector consists of a sequence of one or more characters from the set: `+`, `-`, `*`, `/`, `&`, `=`, `>`, `|`, `<`, `~`, and `@`. Note that `--` (double minus) is not allowed for parsing reasons.

```
[ 100@100
>>> 100@100 "creates a Point object"

[ 3 + 4
>>> 7

[ 10 - 1
>>> 9

[ 4 <= 3
>>> false
```
## 5.2 Three types of messages

```
(4/3) * 3 == 4
>>> true "equality is just a binary message, and Fractions are exact"

(3/4) == (3/4)
>>> false "two equal Fractions are not the same object"
```

**Important** Binary messages are messages that require exactly one argument and whose selector is composed of a sequence of characters from: +, -, *, /, &, =, >, |, <, ~, and @. -- is not possible. They follow the syntactic template: receiver selector argument.

### Keyword messages

Keyword messages are messages that require one or more arguments and whose selector consists of one or more keywords each ending in :. Keyword messages follow the syntactic template: `receiver selectorWordOne: argumentOne wordTwo: argumentTwo`.

Each keyword takes an argument. Hence `r:g:b:` is a method with three arguments, `playFileNamed:` and `at:` are methods with one argument, and `at:put:` is a method with two arguments. To create an instance of the class `Color` one can use the method `r:g:b:` (as in `Color r: 1 g: 0 b: 0`), which creates the color red. Note that the colons are part of the selector.

**Note** In Java or C++, the method invocation `Color r: 1 g: 0 b: 0` would be written `Color RGB(1, 0, 0)`.

```
1 to: 10
>>> (1 to: 10) "creates an interval"

Color r: 1 g: 0 b: 0
>>> Color red "creates a new color"

12 between: 8 and: 15
>>> true

nums := Array newFrom: (1 to: 5).
nums at: 1 put: 6.
nums
>>> #(6 2 3 4 5)
```

**Important** Keyword messages are messages that require one or more arguments. Their selector consists of one or more keywords each ending in a colon (:). They follow the syntactic template: `receiver selectorWordOne: argumentOne wordTwo: argumentTwo`.
<figure><img src="image_46.png" /><figcaption>**Figure 5.3:** Unary messages are sent first so Color yellow is sent. This returns a color</figcaption></figure>

## 5.3 Message composition

The three types of messages each have different precedence, which allows them to be composed in an elegant way and with few parentheses.

* Unary messages are always sent first, then binary messages and finally, keyword messages.

* Messages in parentheses are sent prior to any other messages.

* Messages of the same kind are evaluated from left to right.

These rules lead to a very natural reading order. If you want to be sure that your messages are sent in the order that you want, you can always add more parentheses, as shown in Figure 5.3. In this figure, the message *yellow* is an unary message and the message *color*: a keyword message, therefore the message *Color yellow* is sent first. However as message sends in parentheses are sent first, putting (unnecessary) parentheses around *Color yellow* just emphasizes that it will be sent first. The rest of the section illustrates each of these points.

### Unary > Binary > Keywords

Unary messages are sent first, then binary messages, and finally keyword messages. We also say that unary messages have a higher priority over the other types of messages.

**Important** *Rule one.* Unary messages are sent first, then binary messages, and finally keyword based messages. Unary > Binary > Keyword

As these examples show, Pharo's syntax rules generally ensure that message sends can be read in a natural way:

```
1000 factorial / 999 factorial
>>> 1000

2 raisedTo: 1 + 3 factorial
>>> 128
```

Unfortunately the rules are a bit too simplistic for arithmetic message sends, so you need to introduce parentheses whenever you want to impose a priority over binary operators:
<figure><img src="image_47.png" /><figcaption>**Figure 5.4:** Binary messages are sent before keyword</figcaption></figure>

```
1 + 2 * 3
>>> 9
1 + (2 * 3)
>>> 7
```

**Example 1.** In the message aPen color: Color yellow, there is one unary message yellow sent to the class Color and a keyword message color: sent to aPen. Unary messages are sent first so the message send Color yellow is sent (1). This returns a color object which is passed as argument of the message aPen color: aColor (2) as shown in the following script. Figure 5.3 shows graphically how messages are sent.

```
aPen color: Color yellow
"unary message is sent first"
(1) Color yellow
>>> aColor
"keyword message is sent next"
(2) aPen color: aColor
```

**Example 2.** In the message aPen go: 100 + 20, there is a binary message + 20 and a keyword message go:. Binary messages are sent prior to keyword messages so 100 + 20 is sent first (1): the message + 20 is sent to the object 100 and returns the number 120. Then the message aPen go: 120 is sent with 120 as argument (2). The following example shows how the message send is executed:

```
aPen go: 100 + 20
"binary message first"
(1) 100 + 20
>>> 120
"then keyword message"
(2) aPen go: 120
```

**Example 3.** As an exercise we let you decompose the evaluation of the message Pen new go: 100 + 20 which is composed of one unary, one keyword and one binary message (see Figure 5.5).
<figure><img src="image_48.png" /><figcaption>**Figure 5.5:** Decomposing Pen new go: 100 +</figcaption></figure>

<figure><img src="image_49.png" /><figcaption>**Figure 5.6:** Decomposing Pen new</figcaption></figure>

## Parentheses first

Parenthesised messages are sent prior to other messages.

<figure><img src="image_50.png" /></figure>

Here we need the parentheses to force sending lowMajorScaleOn: before play.

<figure><img src="image_51.png" /></figure>

**Important** Rule two. Parenthesised messages are sent prior to other messages. (Msg) > Unary > Binary > Keyword

**Example 4.** The message (65@325 extent: 134@100) center returns the center of a rectangle whose top left point is (65, 325) and whose size is 134x100. The following script shows how the message is decomposed and sent. First the message between parentheses is sent. It contains two binary messages, 65@325 and 134@100, that are sent first and return points, and a keyword message extent: which is then sent and returns a rectangle. Finally the unary message center is sent to the rectangle and a point is returned. Evaluating the message without parentheses would lead to an error because the object 100 does not understand the message center.

<figure><img src="image_52.png" /></figure>
### 5.3 Message composition

<figure><img src="image_53.png" /></figure>

#### From left to right

Now we know how messages of different kinds or priorities are handled. The final question to be addressed is how messages with the same priority are sent. They are sent from the left to the right. Note that you already saw this behaviour in the previous script where the two point creation messages (@) were sent first.

The following script shows that execution from left to right for messages of the same type reduces the need for parentheses.

<figure><img src="image_54.png" /></figure>

**Important** Rule three. When the messages are of the same kind, the order of evaluation is from left to right.

**Example 5.** In the message sends Pen new down all messages are unary messages, so the leftmost one, Pen new, is sent first. This returns a newly created pen to which the second message down is sent, as shown in Figure 5.6.

#### Arithmetic inconsistencies

The message composition rules are simple but they result in inconsistency for the execution of arithmetic message sends expressed in terms of binary messages. Here we see the common situations where extra parentheses are needed.

<figure><img src="image_55.png" /></figure>
<figure><img src="image_56.png" /><figcaption>**Figure 5.7:** The two messages + and * are of the same kind so their execution is from left to right.</figcaption></figure>

```
1 + (1/3)
>>> (4/3)

1/3 + 2/3
>>> (7/9) "and not 1"

(1/3) + (2/3)
>>> 1
```

**Example 6.** In the message sends `20 + 2 * 5`, there are only binary messages `+` and `*`. However in Pharo there is no special priority for the operations `+` and `*`. They are just binary messages, hence `*` does not have priority over `+`. Here the leftmost message `+` is sent first, and then the `*` is sent to the result as shown in the following script and Figure 5.7.

```
"As there is no priority among binary messages, the leftmost message +
is evaluated first
even if by the rules of arithmetic the * should be sent first."

20 + 2 * 5
(1) 20 + 2
>>> 22
(2) 22 * 5
>>> 110
```

As shown in the previous example the result of this message send is not 30 but 110. This result is perhaps unexpected but follows directly from the rules used to send messages. This is the price to pay for the simplicity of the Pharo model. To get the correct result, we should use parentheses. When messages are enclosed in parentheses, they are evaluated first. Hence the message send `20 + (2 * 5)` returns the result as shown by the following script and Figure 5.8.

```
"The messages surrounded by parentheses are evaluated first therefore *
is sent prior to + which produces the correct behaviour."

20 + (2 * 5)
(1) (2 * 5)
>>> 10
(2) 20 + 10
>>> 30
```
## 5.4 Hints for identifying keyword messages

<figure><img src="image_57.png" /><figcaption>**Figure 5.8:** Parenthesized expressions are executed first.</figcaption></figure>

<figure><img src="image_58.png" /><figcaption>**Figure 5.9:** Equivalent messages using parentheses.</figcaption></figure>

<figure><img src="image_59.png" /><figcaption>**Figure 5.10:** Equivalent messages using parentheses.</figcaption></figure>

**Note** Arithmetic operators such as + and * do not have different priority. + and * are just binary messages, therefore * does not have priority over +. Use parentheses to obtain the desired result.

<table><caption>Table: Message sends and their fully parenthesized equivalents</caption><thead><tr><td>Implicit precedence</td><td>Explicitly parenthesized equivalent</td></tr></thead><tbody><tr><td>aPen color: Color yellow</td><td>aPen color: (Color yellow)</td></tr><tr><td>aPen go: 100 + 20</td><td>Pen go: (100 + 20)</td></tr><tr><td>aPen penSize: aPen penSize + 2</td><td>aPen penSize: ((aPen penSize) + 2)</td></tr><tr><td>2 factorial + 4</td><td>(2 factorial) + 4</td></tr></tbody></table>

Note that the first rule stating that unary messages are sent prior to binary and keyword messages avoids the need to put explicit parentheses around them. Table above shows message sends written following the rules and equivalent message sends if the rules would not exist. Both message sends result in the same effect or return the same value.

## 5.4 Hints for identifying keyword messages

Often beginners have problems understanding when they need to add parentheses. Let's see how keywords messages are recognized by the compiler.
## Parentheses or not?

The characters [], ( and ) delimit distinct areas. Within such an area, a keyword message is the longest sequence of words terminated by : that is not cut by the characters ., or ;. When the characters [], ( and { surround some words with colons, these words participate in the keyword message *local* to the area defined.

In this example, there are two distinct keyword messages: `rotateBy:magnify:smoothing:` and `at:put:`.

```
aDict
    at: (rotatingForm
          rotateBy: angle
          magnify: 2
          smoothing: 1)
    put: 3
```

**Note** The characters [], ( and ) delimit distinct areas. Within such an area, a keyword message is the longest sequence of words terminated by : that is not cut by the characters ., or ;. When the characters [], ( and ) surround some words with colons, these words participate in the keyword message *local* to the area defined.

## Precedence hints

If you have problems with these precedence rules, you may start simply by putting parentheses whenever you want to distinguish two messages having the same precedence.

The following piece of code does not require parentheses because the message `send x isNil` is unary, and is sent prior to the keyword message `ifTrue:`.

```
(x isNil)
    ifTrue: [...]
```

The following code requires parentheses because the messages `includes:` and `ifTrue:` are both keyword messages.

```
ord := OrderedCollection new.
    (ord includes: $a)
    ifTrue: [...]
```

Without parentheses the unknown message `includes:ifTrue:` would be sent to the collection!

## When to use [ ] or ( )

You may also have problems understanding when to use square brackets (blocks) rather than parentheses. The basic principle is that you should use
[ ] when you do not know how many times, potentially zero, an expression should be executed. [ expression ] will create a block closure (an object, as always) from expression, which may be executed zero or more times, depending on the context. (Recall from Chapter: Syntax in a Nutshell that an expression can either be a message send, a variable, a literal, an assignment or a block.)

Following this principle, the conditional branches of `ifTrue`: or `ifTrue:if-False`: require blocks. Similarly, both the receiver and the argument of the `whileTrue`: message require the use of square brackets since we do not know how many times either the receiver (the loop conditional) or the argument (the "loop body") will be executed.

Parentheses, on the other hand, only affect the order of sending messages. So in `()` expression, the expression will *always* be executed exactly once.

```javascript
[ "both the receiver and the argument must be blocks"
[ x isReady ] whileTrue: [ y doSomething ]

"the argument is evaluated more than once, so must be a block"
4 timesRepeat: [ Beeper beep ]

"receiver is evaluated once, so is not a block"
( x isReady) ifTrue: [ y doSomething ]
```

## 5.5 Expression sequences

Expressions (i.e., message sends, assignments and so on) separated by periods are evaluated in sequence. Note that there is no period between a variable definition (the `| box |` section) and the following expressions. The value of a sequence is the value of the last expression. The values returned by all the expressions except the last one are ignored. Note that the period is a separator between expressions, and not a terminator. Therefore a final period is optional.

```javascript
| box |
box := 20@30 corner: 60@90.
box containsPoint: 40@50
>>> true
```

## 5.6 Cascaded messages

Pharo offers a way to send multiple messages to the same receiver using a semicolon (;). This is called the cascade in Pharo jargon. It follows the pattern: `expression msg1; msg2`

```javascript
Transcript show: 'Pharo is '.
Transcript show: 'fun '.
Transcript cr.
```
is equivalent to:

```
Transcript
    show: 'Pharo is';
    show: 'fun ';
cr
```

Note that the object receiving the cascaded messages can itself be the result of a message send. In fact, the receiver of all the cascaded messages is the receiver of the first message involved in a cascade. In the following example, the first cascaded message is `setX: setY` since it is followed by a cascade. The receiver of the cascaded message `setX: setY:` is the newly created point resulting from the evaluation of `Point new`, and not `Point`. The subsequent message `isZero` is sent to that same receiver.

```
Point new setX: 25 setY: 35; isZero
>>> false
```

Important expression `msg1`. expression `msg2` is equivalent to expression `msg1; msg2`

## 5.7 Chapter summary

* A message is always sent to an object named the *receiver*, which itself may be the result of other message sends.

* There are three types of messages: *unary*, *binary*, and *keyword*.

* Unary messages are messages that do not require any argument. They are of the form of *receiver selector*.

* Binary messages are messages that involve two objects, the receiver and another object, whose selector is composed of one or more characters from the following list: `+`, `-`, `*`, `/`, `|`, `&`, `=`, `>`, `<`, `~`, and `@`. They are of the form: *receiver selector* argumentOne *wordOne*: argumentOne *wordTwo*: argumentTwo.

* Keyword messages are messages that involve more than one object and that contain at least one colon character (`:`). They are of the form: `receiver selectorWordOne: argumentOne wordTwo: argumentTwo`.

* **Rule One.** Unary messages are sent first, then binary messages, and finally keyword messages.

* **Rule Two.** Messages in parentheses are sent before any others.

* **Rule Three.** When the messages are of the same type, the order of evaluation is from left to right.

* In Pharo, traditional arithmetic operators such as `+` and `*` have the same priority. `+` and `*` are just binary messages, therefore `*` does not
5.7 Chapter summary

have priority over +. You must use parentheses to obtain the desired
arithmetical order of operations.
<figure><img src="image_60.png" /></figure>
CHAPTER 6

# The Pharo object model

The Pharo programming model is heavily inspired by the one of Smalltalk. It is simple and uniform: everything is an object, and objects communicate only by sending each other messages. Instance variables are private to the object. Methods are all public and dynamically looked up (late-bound). In this chapter we present the core concepts of the Pharo object model. We revisit concepts such as self and super and define precisely their semantics. Then we discuss the consequences of representing classes as objects. This will be extended in Chapter: Classes and Metaclasses.

## 6.1 The rules of the model

The object model is based on a set of simple rules that are applied *uniformly*.
The rules are as follows:

**Rule 1.** Everything is an object.

**Rule 2.** Every object is an instance of a class.

**Rule 3.** Every class has a superclass.

**Rule 4.** Everything happens by sending messages.

**Rule 5.** Method lookup dynamically follows the inheritance chain.

Let us look at each of these rules in some detail.

## 6.2 Everything is an Object

The mantra *everything is an object* is highly contagious. After only a short while working with Pharo, you will start to be surprised at how this rule
simplifies everything you do. Integers, for example, are truly objects, so you
can send messages to them, just as you do to any other object. At the end of
this chapter, we added an implementation note on the object implementation
for the curious reader.

```
[ "send '+ 4' to 3, yielding 7"
  3 + 4
>>> 7

[ "send factorial, yielding a big number"
  20 factorial
>>> 2432902008176640000
```

The object 7 is different than the object returned by `20 factorial`, but because they are both polymorphic objects, none of the code, not even the implementation of `factorial`, needs to know about this.

Coming back to *everything is an object* rule, perhaps the most fundamental consequence of this rule is that classes are objects too. Classes are not second-class objects: they are really first-class objects that you can send messages to, inspect, and change. This means that Pharo is a truly reflective system, which gives a great deal of expressive power to developers.

**Important** Classes are objects too.

## 6.3 Every object is an instance of a class

Every object has a class; you can find out which one by sending it the message `class`.

```
[ 1 class
>>> SmallInteger

[ 20 factorial class
>>> LargePositiveInteger

[ 'hello' class
>>> ByteString

[ (4@5) class
>>> Point

[ Object new class
>>> Object
```

A class defines the *structure* of its instances via instance variables, and the *behavior* of its instances via methods. Each method has a name, called its *selector*, which is unique within the class.

Since *classes are objects*, and *every object is an instance of a class*, it follows that classes must also be instances of classes. A class whose instances are classes
is called a *metaclass*. Whenever you create a class, the system automatically creates a metaclass for you. The metaclass defines the structure and behavior of the class that is its instance. 99% of the time you will not need to think about metaclasses, and may happily ignore them. (We will have a closer look at metaclasses in Chapter : Classes and Metaclasses.)

## 6.4 Instance structure and behavior

Now we will briefly present how we specify the structure and behavior of
instances.

### Instance variables

Instance variables in Pharo are private to the *instance* itself. This is in contrast to Java and C++, which allow instance variables (also known as *fields* or *member variables*) to be accessed by any other instance that happens to be of the same class. We say that the *encapsulation boundary* of objects in Java and C++ is the class, whereas in Pharo it is the instance.

In Pharo, two instances of the same class cannot access each other's instance variables unless the class defines *accessor methods*. There is no language syntax that provides direct access to the instance variables of any other object. (Actually, a mechanism called reflection does provide a way to ask another object for the values of its instance variables; meta-programming is intended for writing tools like the object inspector, whose sole purpose is to look inside other objects.)

Instance variables can be accessed by name in any of the instance methods of the class that defines them, and also in the methods defined in its subclasses. This means that Pharo instance variables are similar to *protected* variables in C++ and Java. However, we prefer to say that they are private, because it is considered bad style in Pharo to access an instance variable directly from a subclass.

### Instance encapsulation example

The method `Point>>dist:` computes the distance between the receiver and another point. The instance variables `x` and `y` of the receiver are accessed directly by the method body. However, the instance variables of the other point must be accessed by sending it the messages `x` and `y`.

```
Point >> dist: aPoint
    "Answer the distance between aPoint and the receiver."

| dx dy |
dx := aPoint x - x.
dy := aPoint y - y.
```
```math
  ^ ((dx * dx) + (dy * dy)) sqrt
```
```
1@1 dist: 4@5
>>> 5.0
```

The key reason to prefer instance-based encapsulation to class-based encapsulation is that it enables different implementations of the same abstraction to coexist. For example, the method `dist:` need not know or care whether the argument `aPoint` is an instance of the same class as the receiver. The argument object might be represented in polar coordinates, or as a record in a database, or on another computer in a distributed system. As long as it can respond to the messages `x` and `y`, the code of method `dist` (shown above) will still work.

## Methods

All methods are *public* and *virtual* (i.e., dynamically looked up). Methods are grouped into *protocols* that indicate their intent. Some common protocol names have been established by convention, for example, *accessing* for all accessor methods, and *initialization* for establishing a consistent initial state for the object. The protocol *private* is sometimes used to group methods that should not be seen from outside. Nothing, however, prevents you from sending a message that is implemented by such a "private" method.

Methods can access all instance variables of the object. Some developers prefer to access instance variables only through accessors. This practice has some value, but it also clutters the interface of your classes, and worse, exposes its private state to the world.

## 6.5 The instance side and the class side

Since classes are objects, they can have their own instance variables and their own methods. We call these *class instance variables* and *class methods*, but they are really no different from ordinary instance variables and methods: They simply operate on different objects (classes in this case). An instance variable describes instance state and a method describes instance behavior. Similarly, class instance variables are just instance variables defined by a metaclass (and describe the state of classes - instances of metaclasses), and class methods are just methods defined by a metaclass (and that will be executed on classes).

A class and its metaclass are two separate classes, even though the former is an instance of the latter. However, this is largely irrelevant to you as a programmer: you are concerned with defining the behavior of your objects and the classes that create them.

For this reason, the browser helps you to browse both class and metaclass as if they were a single thing with two "sides": the *instance side* and the *class side*, as shown in Figure 6.1. By default, when you select a class in the browser, you're
6.5 The instance side and the class side

<figure><img src="image_61.png" /><figcaption>Figure 6.1: Browsing a class and its metaclass</figcaption></figure>

browsing the *instance side* (i.e., the methods that are executed when messages are sent to an *instance of Color*). Clicking on the **Class side** button switches you over to the **class side** (*the methods that will be executed when messages are sent to the class Color itself*).

For example, Color blue sends the message blue to the class Color. You will therefore find the method blue defined on the class side of Color, not on the instance side.

```
"Class-side method blue (convenient instance creation method)"
aColor := Color blue.
```

```
>>> Color blue
"Color instances are self-evaluating"
```

```
"Instance-side accessor method red (returns the red RGB value)"
Color blue red
```

```
>>> 0.0
```

```
"Instance-side accessor method blue (returns the blue RGB value)"
Color blue blue
```

```
>>> 1.0
```

You define a class by filling in the template proposed on the instance side. When you accept this template, the system creates not just the class that you defined, but also the corresponding metaclass (which you can then edit by clicking on the **Class side** button). The only part of the metaclass creation template that makes sense for you to edit directly is the list of the metaclass's instance variable names.

Once a class has been created, browsing its instance side (**Class side** unchecked) lets you edit and browse the methods that will be possessed by instances of that class (and of its subclasses).
## Class methods

Class methods can be quite useful; browse `Color class` for some good examples. You will see that there are two kinds of methods defined on a class: *instance creation methods*, like `Color class>>blue`, and those that perform a utility function, like `Color class>>wheel`. This is typical, although you will occasionally find class methods used in other ways.

It is convenient to place utility methods on the class side because they can be executed without having to create any additional objects first. Indeed, many of them will contain a comment designed to make it easy to execute them.

Browse method `Color class>>wheel:`, double-click just at the beginning of the comment `"(Color wheel: 12) inspect"` and press `CMD-d`. You will see the effect of executing this method.

For those familiar with Java and C++, class methods may seem similar to static methods. However, the uniformity of the Pharo object model (where classes are just regular objects) means that they are somewhat different: whereas Java static methods are really just statically-resolved procedures, Pharo class methods are dynamically-dispatched methods. This means that inheritance, overriding and super-sends work for class methods in Pharo, whereas they don't work for static methods in Java.

## Class instance variables

With ordinary instance variables, all the instances of a class have the same set of variable names (though each instance has its own private set of values), and the instances of its subclasses inherit those names. The story is exactly the same with class instance variables: each class has its own private class instance variables. A subclass will inherit those class instance variables, but the subclass will have its own private copies of those variables. Just as objects don't share instance variables, neither do classes and their subclasses share class instance variables.

For example, you could use a class instance variable called `count` to keep track of how many instances you create of a given class. However, any subclass would have its own `count` variable, so subclass instances would be counted separately.

### Example: Class instance variables and subclasses

Suppose we define the class `Dog`, and its subclass `Hyena`. Suppose that we add a `count` class instance variable to the class `Dog` (i.e. we define it on the metaclass `Dog class`). Hyena will naturally inherit the class instance variable `count` from `Dog`.

```
Object subclass: #Dog
instanceVariableNames: ''
```
### 6.5 The instance side and the class side

```groovy
classVariableNames: ''
package: 'PBE-CIV'

Dog class
    instanceVariableNames: 'count'

Dog subclass: #Hyena
    instanceVariableNames: ''
    classVariableNames: ''
    package: 'PBE-CIV'
```

Now suppose we define class methods for `Dog` to initialize its count to 0, and to increment it when new instances are created:

```groovy
Dog class >> initialize
    count := 0.

Dog class >> new
    count := count +1.
    ^ super new

Dog class >> count
    ^ count
```

Now when we create a new `Dog`, the count value of the class `Dog` is increased, and so is that of the class `Hyena` (but the `hyenas` are counted separately).

**Side note:** Notice the use of `initialize` on the classes, in the following code. In `Pharo`, when you instantiate an object such as `Dog new`, `initialize` is called automatically as part of the new message send (you can see for yourself by browsing `Behavior>>new`). But with classes, simply defining them does not automatically call `initialize`, and so we have to call it explicitly here. By default class `initialize` methods are automatically executed only when classes are loaded. See also the discussion about lazy initialization, below.

```groovy
Dog initialize.
Hyena initialize.
Dog count
>>> 0
Hyena count
>>> 0

| aDog |
aDog := Dog new.
Dog count
>>> 1 "Incremented"
Hyena count
>>> 0 "Still the same"
```

Class instance variables are private to a class in exactly the same way that instance variables are private to an instance. Since classes and their instances are different objects, this has the following consequences:
1. A class does not have access to the instance variables of its own instances. So, the class Color does not have access to the variables of an object instantiated from it, aColorRed. In other words, just because a class was used to create an instance (using new or a helper instance creation method like Color red), it doesn't give the class any special direct access to that instance's variables. The class instead has to go through the accessor methods (a public interface) just like any other object.

2. The reverse is also true: an *instance* of a class does not have access to the class instance variables of its class. In our example above, aDog (an individual instance) does not have direct access to the count variable of the Dog class (except, again, through an accessor method).

**Important** A class does not have access to the instance variables of its own instances. An instance of a class does not have access to the class instance variables of its class.

For this reason, instance initialization methods must always be defined on the instance side, the class side has no access to instance variables, and so cannot initialize them! All that the class can do is to send initialization messages, using accessors, to newly created instances.

Java has nothing equivalent to class instance variables. Java and C++ static variables are more like Pharo class variables (discussed in Section 6.9), since in those languages all of the subclasses and all of their instances share the same static variable.

## Example: Defining a Singleton

The Singleton pattern provides a typical example of the use of class instance variables and class methods. Imagine that we would like to implement a class WebServer, and to use the Singleton pattern to ensure that it has only one instance.

We define the class WebServer as follows.

```ruby
Object subclass: #WebServer
    instanceVariableNames: 'sessions'
    classVariableNames: ''
    package: 'Web'
```

Then, clicking on the **Class** side button, we add the (class) instance variable `uniqueInstance`.

```ruby
WebServer class
    instanceVariableNames: 'uniqueInstance'
```

As a result, the class `WebServer` class will have a new instance variable (in addition to the variables that it inherits from `Behavior`, such as `superclass`)
and `methodDict`). It means that the value of this extra instance variable will describe the instance of the class `WebServer` class i.e. the class `WebServer`.

```java
Object class allInstVarNames
>>> "#('superclass' 'methodDict' 'format' 'layout' 'instanceVariables'
'organization' 'subclasses' 'name' 'classPool' 'sharedPools'
'environment' 'category' 'traitComposition' 'localSelectors')"

WebServer class allInstVarNames
>>> "#('superclass' 'methodDict' 'format' 'layout' 'instanceVariables'
'organization' 'subclasses' 'name' 'classPool' 'sharedPools'
'environment' 'category' 'traitComposition' 'local selectors')"
#uniqueInstance)
```

We can now define a class method named `uniqueInstance`, as shown below. This method first checks whether `uniqueInstance` has been initialized. If it has not, the method creates an instance and assigns it to the class instance variable `uniqueInstance`. Finally the value of `uniqueInstance` is returned. Since `uniqueInstance` is a class instance variable, this method can directly access it.

```java
WebServer class >> uniqueInstance
    uniqueInstance ifNil: [ uniqueInstance := self new ].
    ^ uniqueInstance
```

The first time that `WebServer` `uniqueInstance` is executed, an instance of the class `WebServer` will be created and assigned to the `uniqueInstance` variable. The next time, the previously created instance will be returned instead of creating a new one. (This pattern, checking if a variable is `nil` in an accessor method, and initializing its value if it is `nil`, is called *lazy initialization*).

Note that the instance creation code in the code above.

is written as `self new` and not as `WebServer new`. What is the difference? Since the `uniqueInstance` method is defined in `WebServer` class, you might think that there is no difference. And indeed, until someone creates a subclass of `WebServer`, they are the same. But suppose that `ReliableWebServer` is a subclass of `WebServer`, and inherits the `uniqueInstance` method. We would clearly expect `ReliableWebServer uniqueInstance` to answer a `ReliableWebServer`. Using `self` ensures that this will happen, since `self` will be bound to the respective receiver, here the classes `WebServer` and `ReliableWebServer`. Note also that `WebServer` and `ReliableWebServer` will each have a different value for their `uniqueInstance` instance variable.

**A note on lazy initialization.** *Do not over-use the lazy initialization pattern.* The setting of initial values for instances of objects generally belongs in the `initialize` method. Putting initialization calls only in `initialize` helps from a readability perspective – you don’t have to hunt through all the accessor methods to see what the initial values are. Although it may be tempting to instead
initialize instance variables in their respective accessor methods (using `ifNil:` checks), avoid this unless you have a good reason.

For example, in our `uniqueInstance` method above, we used lazy initialization because users won't typically expect to call `WebServer initialize`. Instead, they expect the class to be "ready" to return new unique instances. Because of this, lazy initialization makes sense. Similarly, if a variable is expensive to initialize (opening a database connection or a network socket, for example), you will sometimes choose to delay that initialization until you actually need it.

## 6.6 Every class has a superclass

Each class in Pharo inherits its behaviour and the description of its structure from a single superclass. This means that Smalltalk has single inheritance.

* `SmallInteger superclass`
  * `>>> Integer`

* `Integer superclass`
  * `>>> Number`

* `Number superclass`
  * `>>> Magnitude`

* `Magnitude superclass`
  * `>>> Object`

* `Object superclass`
  * `>>> ProtoObject`

* `ProtoObject superclass`
  * `>>> nil`

Traditionally the root of an inheritance hierarchy is the class `Object` (since everything is an object). In Pharo, the root is actually a class called `ProtoObject`, but you will normally not pay any attention to this class. `ProtoObject` encapsulates the minimal set of messages that all objects *must* have and `ProtoObject` is designed to raise as many as possible errors (to support proxy definition). However, most classes inherit from `Object`, which defines many additional messages that almost all objects understand and respond to. Unless you have a very good reason to do otherwise, when creating application classes you should normally subclass `Object`, or one of its subclasses.

A new class is normally created by sending the message `subclass: instance-VariableNames: ...` to an existing class. There are a few other methods to create classes. To see what they are, have a look at `Class` and its subclass `creation protocol`.

Although Pharo does not provide multiple inheritance, it supports a mechanism called `Traits` for sharing behaviour across unrelated classes. Traits are
collections of methods that can be reused by multiple classes that are not
related by inheritance. Using traits allows one to share code between different
classes without duplicating code.

**Abstract methods and abstract classes**

An abstract class is a class that exists to be subclassed, rather than to be
instantiated. An abstract class is usually incomplete, in the sense that it does
not define all of the methods that it uses. The "placeholder" methods, those
that the other methods assume to be (re)defined are called abstract methods.

Pharo has no dedicated syntax to specify that a method or a class is abstract. Instead, by convention, the body of an abstract method consists of the expression `self subclassResponsibility`. This indicates that subclasses have the responsibility to define a concrete version of the method. `self subclassResponsibility` methods should always be overridden, and thus should never be executed. If you forget to override one, and it is executed, an exception will be raised.

Similarly, a class is considered abstract if one of its methods is abstract. Nothing actually prevents you from creating an instance of an abstract class; everything will work until an abstract method is invoked.

Example: the abstract class Magnitude

Magnitude is an abstract class that helps us to define objects that can be com-
pared to each other. Subclasses of Magnitude should implement the methods
<, = and hash. Using such messages, Magnitude defines other methods such
as >, >=, <=, max:, min: between: and: and others for comparing objects. Such
methods are inherited by subclasses. The method Magnitude>>< is abstract,
and defined as shown in the following script.

```ruby
< aMagnitude
  "Answer whether the receiver is less than the argument."
  ^self subclassResponsibility
```

By contrast, the method >= is concrete, and is defined in terms of <.

```ruby
>= aMagnitude
  "Answer whether the receiver is greater than or equal to the
   argument."
 ^(self < aMagnitude) not
```

The same is true of the other comparison methods (they are all defined in
terms of the abstract method <).
Character is a subclass of Magnitude; it overrides the `<` method (which, if you recall, is marked as abstract in Magnitude by the use of `self subclassResponsibility`) with its own version (see the method definition below).

Character also explicitly defines methods = and hash; it inherits from Magnitude the methods `>=`, `<=`, `=~` and others.

<table><tr><td>&lt; aCharacter</td><td>"Answer true if the receiver's value &lt; aCharacter's value."</td></tr><tr><td>^self asciiValue &lt; aCharacter asciiValue</td><td></td></tr></table>

## Traits

A trait is a collection of methods that can be included in the behaviour of a class without the need for inheritance. This makes it easy for classes to have a unique superclass, yet still share useful methods with otherwise unrelated classes.

To define a new trait, simply right-click in the class pane and select Add Trait, or replace the subclass creation template by the trait creation template, below.

<table><tr><td>Trait named: #TAuthor</td></tr><tr><td>uses: { }</td></tr><tr><td>package: 'PBE-LightsOut'</td></tr></table>

Here we define the trait TA author in the package PBE-LightsOut. This trait does not use any other existing traits. In general we can specify a trait composition expression of other traits to use as part of the `uses:` keyword argument. Here we simply provide an empty array.

Traits may contain methods, but no instance variables. Suppose we would like to be able to add an author method to various classes, independent of where they occur in the hierarchy.

We might do this as follows:

<table><tr><td>TAuthor &gt;&gt; author</td></tr><tr><td>"Returns author initials"</td></tr><tr><td>^ 'on' "oscar nierstrasz"</td></tr></table>

Now we can use this trait in a class that already has its own superclass, for instance the LOGame class that we defined in Chapter: A First Application. We simply modify the class creation template for LOGame to include a `uses:` keyword argument that specifies that TA author should be used.

<table><tr><td>BorderedMorph subclass: #LOGame</td></tr><tr><td>uses: TA author</td></tr><tr><td>instanceVariableNames: 'cells'</td></tr><tr><td>classVariableNames: ''</td></tr></table>
## 6.7 Everything happens by sending messages

```groovy
package: 'PBE-LightsOut'
```

If we now instantiate `LOGame`, it will respond to the author message as expected.

```groovy
LOGame new author
>>> 'on'
```

Trait composition expressions may combine multiple traits using the `+` operator. In case of conflicts (i.e., if multiple traits define methods with the same name), these conflicts can be resolved by explicitly removing these methods (with `-`), or by redefining these methods in the class or trait that you are defining. It is also possible to alias methods (with `@`), providing a new name for them.

Traits are used in the system kernel. One good example is the class `Behavior`.

```groovy
Object subclass: #Behavior
    uses: TPureBehavior @
        {#basicAddTraitSelector:withMethod:->#addTraitSelector:withMethod:}
    instanceVariableNames: 'superclass methodDict format'
    classVariableNames: 'ObsoleteSubclasses'
    package: 'Kernel-Classes'
```

Here we see that the method `addTraitSelector:withMethod:` defined in the trait `TPureBehavior` has been aliased to `basicAddTraitSelector:withMethod:`.

## 6.7 Everything happens by sending messages

This rule captures the essence of programming in Pharo.

In procedural programming (and in some static features of some object-oriented languages such as Java), the choice of which piece of code to execute when a procedure is called is made by the caller. The caller chooses the procedure to execute *statically*, by name.

In Pharo, we do *not* "invoke methods". Instead, we *send messages*. This is just a terminology point but it is significant. It implies that this is not the responsibility of the client to select the method to be executed, it is the one of the receiver of the message.

When sending a message, we do not decide which method will be executed. Instead, we *tell* an object to do something for us by sending it a message. A message is nothing but a name and a list of arguments. The receiver then decides how to respond by selecting its own *method* for doing what was asked. Since different objects may have different methods for responding to the same message, the method must be chosen *dynamically*, when the message is received.
```
3 + 4
>>> 7 "send message + with argument 4 to integer 3"
(1@2) + 4
>>> 5@6 "send message + with argument 4 to point (1@2)"
```

As a consequence, we can send the *same message* to different objects, each of which may have its own method for responding to the message. We do not tell the `SmallInteger 3` or the `Point (1@2)` how to respond to the message `+ 4`. Each has its own method for `+`, and responds to `+ 4` accordingly.

One of the consequences of Pharo's model of message sending is that it encourages a style in which objects tend to have very small methods and delegate tasks to other objects, rather than implementing huge, procedural methods that assume too much responsibility. Joseph Pelrine expresses this principle succinctly as follows:

> "Don't do anything that you can push off onto someone else."

Many object-oriented languages provide both static and dynamic operations for objects. In Pharo there are only dynamic message sends. For example, instead of providing static class operations, we simply send messages to classes (which are simply objects).

Ok, so *nearly* everything in Pharo happens by sending messages. At some point action must take place:

*Variable declarations* are not message sends. In fact, variable declarations are not even executable. Declaring a variable just causes space to be allocated for an object reference.

*Assignments* are not message sends. An assignment to a variable causes that variable name to be freshly bound in the scope of its definition.

*Returns* are not message sends. A return simply causes the computed result to be returned to the sender.

*Primitives* (and Pragmas/annotations) are not message sends. They are implemented in the virtual machine.

Other than these few exceptions, pretty much everything else does truly happen by sending messages. In particular, since there are no *public fields* in Pharo, the only way to update an instance variable of another object is to send it a message asking that it update its own field. Of course, providing setter and getter methods for all the instance variables of an object is not good object-oriented style. Joseph Pelrine also states this very nicely:

> "Don't let anyone else play with your data."
## 6.8 Method lookup follows the inheritance chain

What exactly happens when an object receives a message? This is a two step process: method lookup and method execution.

**Lookup.** First, the method having the same name as the message is looked up.

**Method Execution.** Second, the found method is applied to the receiver with the message arguments: When the method is found, the arguments are bound to the parameters of the method, and the virtual machine executes it.

The lookup process is quite simple:

1. The class of the receiver looks up the method to use to handle the message.

2. If this class does not have that method method defined, it asks its superclass, and so on, up the inheritance chain.

It is essentially as simple as that. Nevertheless there are a few questions that need some care to answer:

* What happens when a method does not explicitly return a value?

* What happens when a class reimplements a superclass method?

* What is the difference between self and super sends?

* What happens when no method is found?

The rules for method lookup that we present here are conceptual; virtual machine implementors use all kinds of tricks and optimizations to speed up method lookup. That's their job, but you should never be able to detect that they are doing something different from our rules.

First let us look at the basic lookup strategy, and then consider these further questions.

### Method lookup

Suppose we create an instance of `EllipseMorph`.

```java
anEllipse ::= EllipseMorph new.
```

If we now send this object the message `defaultColor`, we get the result `Color yellow`.

```java
anEllipse defaultColor
>>> Color yellow
```

The class `EllipseMorph` implements `defaultColor`, so the appropriate method is found immediately.

```java
EllipseMorph >> defaultColor
    "Answer the default color/fill style for the receiver"
    ^ Color yellow
```
<figure><img src="image_62.png" /><figcaption>**Figure 6.2:** Method lookup follows the inheritance hierarchy</figcaption></figure>

In contrast, if we send the message `openInWorld` to an `Ellipse`, the method is not immediately found, since the class `EllipseMorph` does not implement `openInWorld`. The search therefore continues in the superclass, `BorderedMorph`, and so on, until an `openInWorld` method is found in the class `Morph` (see Figure 6.2).

```
Morph >> openInWorld
    "Add this morph to the world."
self openInWorld: self currentWorld
```

## Returning self

Notice that `EllipseMorph>>defaultColor` explicitly returns `Color yellow`, whereas `Morph>>openInWorld` does not appear to return anything.

Actually a method *always* answers a message with a value (which is, of course, an object). The answer may be defined by the `^` construct in the method, but if execution reaches the end of the method without executing a `^`, the method still answers a value - it answers the object that received the message. We usually say that the method *answers self*, because in Pharo the pseudo-variable `self` represents the receiver of the message, much like the keyword `this` in Java. Other languages, such as Ruby, by default return the value of the last statement in the method. Again, this is not the case in Pharo, instead you can imagine that a method without an explicit return ends with `^ self`.

Important `self` represents the receiver of the message.

This suggests that `openInWorld` is equivalent to `openInWorldReturnSelf`, defined below.
6.8 Method lookup follows the inheritance chain

```java
Morph >> openInWorld
    "Add this morph to the world."
    self openInWorld: self currentWorld
    ^ self
```

Why is explicitly writing `^ self` not a so good thing to do? When you return something explicitly, you are communicating that you are returning something of interest to the sender. When you explicitly return `self`, you are saying that you expect the sender to use the returned value. This is not the case here, so it is best not to explicitly return `self`. We only return `self` on special case to stress that the receiver is returned.

This is a common idiom in Pharo, which Kent Beck refers to as *Interesting return value*:

"Return a value only when you intend for the sender to use the value."

**Important** By default (if not specified differently) a method returns the message receiver.

## Overriding and extension

If we look again at the `EllipseMorph` class hierarchy in Figure 6.2, we see that the classes `Morph` and `EllipseMorph` both implement `defaultColor`. In fact, if we open a new morph (`Morph new openInWorld`) we see that we get a blue morph, whereas an ellipse will be yellow by default.

We say that `EllipseMorph overrides` the `defaultColor` method that it inherits from `Morph`. The inherited method no longer exists from the point of view of an`Ellipse`.

Sometimes we do not want to override inherited methods, but rather *extend* them with some new functionality, that is, we would like to be able to invoke the overridden method *in addition to* the new functionality we are defining in the subclass. In Pharo, as in many object-oriented languages that support single inheritance, this can be done with the help of super sends.

A frequent application of this mechanism is in the `initialize` method. Whenever a new instance of a class is initialized, it is critical to also initialize any inherited instance variables. However, the knowledge of how to do this is already captured in the `initialize` methods of each of the superclass in the inheritance chain. The subclass has no business even trying to initialize inherited instance variables!

It is therefore good practice whenever implementing an `initialize` method to send super `initialize` before performing any further initialization:

```java
BorderedMorph >> initialize
    "initialize the state of the receiver"
    super initialize.
```
```pharo
self borderInitialize
```

We need super sends to compose inherited behaviour that would otherwise be overridden.

**Important** It is a good practice that an initialize method start by sending super initialize.

## Self sends and super sends

self represents the receiver of the message and the lookup of the method starts in the class of the receiver. Now what is super? super is not the superclass! It is a common and natural mistake to think this. It is also a mistake to think that lookup starts in the superclass of the class of the receiver.

**Important** self represents the receiver of the message and the method lookup starts in the class of the receiver.

## How do self sends differ from super sends?

Like self, super represents the receiver of the message. Yes you read it well! The only thing that changes is the method lookup. Instead of lookup starting in the class of the receiver, it starts in the superclass of the class of the method where the super send occurs.

**Important** super represents the receiver of the message and the method lookup starts in the superclass of the class of the method where the super send occurs.

We shall see with the following example precisely how this works. Imagine that we define the following three methods:

First we define the method `fullPrintOn:` on class `Morph` that just adds to the stream the name of the class followed by the string 'new' - the idea is that we could execute the resulting string and gets back an instance similar to the receiver.

```ruby
Morph >> fullPrintOn: aStream
        aStream nextPutAll: self class name, ' new'
```

Second we define the method `constructorString` that send the message `fullPrintOn:`.

```ruby
Morph >> constructorString
        ^ String streamContents: [ :s | self fullPrintOn: s ].
```

Finally, we define the method `fullPrintOn:` on the class `BorderedMorph` superclass of `EllipseMorph`. This new method extends the superclass behavior: it invokes it and adds extra behavior.
<figure><img src="image_63.png" /><figcaption>Figure 6.3: self and super sends</figcaption></figure>

```java
BorderedMorph >> fullPrintOn: aStream
aStream nextPutAll: '(.'.
super fullPrintOn: aStream.
aStream
    nextPutAll: ') setBorderWidth: ';
    print: borderWidth;
    nextPutAll: ' borderColor: ', (self colorString: borderColor)
```

Consider the message constructorString sent to an instance of Ellipse-Morph:

```java
EllipseMorph new constructorString
>>> '(EllipseMorph new) setBorderWidth: 1 borderColor: Color black'
```

How exactly is this result obtained through a combination of self and super sends? First, anEllipse constructorString will cause the method constructorString to be found in the class Morph, as shown in Figure 6.3.

The method Morph>>constructorString performs a self send of full-PrintOn:. The message fullPrintOn: is looked up starting in the class EllipseMorph, and the method BorderedMorph>>fullPrintOn: is found in BorderedMorph (see Figure 6.3). What is critical to notice is that the self send causes the method lookup to start again in the class of the receiver, namely the class of anEllipse.

At this point, BorderedMorph>>fullPrintOn: does a super send to extend the fullPrintOn: behaviour it inherits from its superclass. Because this is a super send, the lookup now starts in the superclass of the class where the super send occurs, namely in Morph. We then immediately find and evaluate Morph>>fullPrintOn:.
## Stepping back

A self send is dynamic in the sense that by looking at the method containing it, we cannot predict which method will be executed. Indeed an instance of a subclass may receive the message containing the self expression and redefine the method in that subclass. Here *EllipseMorph* could redefine the method `fullPrintOn:` and this method would be executed by method `constructorString`. Note that by only looking at the method `constructorString`, we cannot predict which `fullPrintOn:` method (either the one of *EllipseMorph*, *BorderedMorph*, or *Morph*) will be executed when executing the method `constructorString`, since it depends on the receiver the `constructorString` message.

**Important** A self send triggers a *method lookup starting in the class of the receiver*. A self send is dynamic in the sense that by looking at the method containing it, we cannot predict which method will be executed.

Note that the super lookup did not start in the superclass of the receiver. This would have caused lookup to start from *BorderedMorph*, resulting in an infinite loop!

If you think carefully about super send and Figure 6.3, you will realize that super bindings are static: all that matters is the class in which the text of the super send is found. By contrast, the meaning of self is dynamic: it always represents the receiver of the currently executing message. This means that *all* messages sent to self are looked up by starting in the receiver's class.

**Important** A super send triggers a method lookup starting in the *super-class of the class of the method performing the super send*. We say that super sends are *static* because just looking at the method we know the class where the lookup should start (the class above the class containing the method).

## Message not understood

What happens if the method we are looking for is not found?

Suppose we send the message `foo` to our ellipse. First the normal method lookup would go through the inheritance chain all the way up to `Object` (or rather `ProtoObject`) looking for this method. When this method is not found, the virtual machine will cause the object to send `self doesNotUnderstand:` `#foo`. (See Figure 6.4.)

Now, this is a perfectly ordinary, dynamic message send, so the lookup starts again from the class *EllipseMorph*, but this time searching for the method `doesNotUnderstand:`. As it turns out, *Object* implements `doesNotUnderstand:`. This method will create a new `MessageNotUnderstood` object which is capable of starting a Debugger in the current execution context.
<figure><img src="image_64.png" /><figcaption>Figure 6.4: Message foo is not understood</figcaption></figure>

Why do we take this convoluted path to handle such an obvious error? Well, this offers developers an easy way to intercept such errors and take alternative action. One could easily override the method `Object>>doesNotUnderstand`: in any subclass of `Object` and provide a different way of handling the error.

In fact, this can be an easy way to implement automatic delegation of messages from one object to another. A Delegator object could simply delegate all messages it does not understand to another object whose responsibility it is to handle them, or raise an error itself!

## 6.9 Shared variables

Now we will look at an aspect of Pharo that is not so easily covered by our five rules: shared variables.

Pharo provides three kinds of shared variables:

1. **Globally shared variables.**

2. **Class variables:** variables shared between instances and classes. (Not to be confused with class instance variables, discussed earlier).

3. **Pool variables:** variables shared amongst a group of classes,

The names of all of these shared variables start with a capital letter, to warn us that they are indeed shared between multiple objects.

### Global variables

In Pharo, all global variables are stored in a namespace called `Smalltalk`, which is implemented as an instance of the class `SystemDictionary`. Global variables are accessible everywhere. Every class is named by a global variable. In addition, a few globals are used to name special or commonly useful objects.
The variable Processor names an instance of ProcessScheduler, the main process scheduler of Pharo

Processor class
>>> ProcessorScheduler

## Other useful global variables

Smalltalk is the instance of SmalltalkImage. It contains many functionality to manage the system. In particular it holds a reference to the main namespace Smalltalk globals. This namespace includes Smalltalk itself since it is a global variable. The keys to this namespace are the symbols that name the global objects in Pharo code. So, for example:

Smalltalk globals at: #Boolean
>>> Boolean

Since Smalltalk is itself a global variable:

Smalltalk globals at: #Smalltalk
>>> Smalltalk
(Smalltalk globals at: #Smalltalk) == Smalltalk
>>> true

World is an instance of PasteUpMorph that represents the screen. World bounds answers a rectangle that defines the whole screen space; all Morphs on the screen are submorphs of World.

ActiveHand is the current instance of HandMorph, the graphical representation of the cursor. ActiveHand's submorphs hold anything being dragged by the mouse.

Undeclared is another dictionary, which contains all the undeclared variables. If you write a method that references an undeclared variable, the browser will normally prompt you to declare it, for example as a global or as an instance variable of the class. However, if you later delete the declaration, the code will then reference an undeclared variable. Inspecting Undeclared can sometimes help explain strange behaviour!

## Using globals in your code

The recommended practice is to strictly limit the use of global variables. It is usually better to use class instance variables or class variables, and to provide class methods to access them. Indeed, if Pharo were to be implemented from scratch today, most of the global variables that are not classes would be replaced by singletons.

The usual way to define a global is just to perform Do it on an assignment to a capitalized but undeclared identifier. The parser will then offer to declare the
<figure><img src="image_65.png" /><figcaption>**Figure 6.5:** Instance and class methods accessing different variables</figcaption></figure>

global for you. If you want to define a global programmatically, just execute `Smalltalk globals at: #AGlobalName put: nil`. To remove it, execute `Smalltalk globals removeKey: #AGlobalName`.

## Class variables

Sometimes we need to share some data amongst all the instances of a class and the class itself. This is possible using *class variables*. The term *class variable* indicates that the lifetime of the variable is the same as that of the class. However, what the term does not convey is that these variables are shared amongst all the instances of a class as well as the class itself, as shown in Figure 6.5. Indeed, a better name would have been *shared variables* since this expresses more clearly their role, and also warns of the danger of using them, particularly if they are modified.

In Figure 6.5 we see that `rgb` and `cachedDepth` are instance variables of `Color`, hence only accessible to instances of `Color`. We also see that `superclass`, `subclass`, `methodDict` and so on are *class instance variables*, i.e., instance variables only accessible to the `Color` class.

But we can also see something new: `ColorRegistry` and `CacheColormaps` are *class variables* defined for `Color`. The capitalization of these variables gives us a hint that they are shared. In fact, not only may all instances of `Color` access these shared variables, but also the `Color` class itself, and any of its subclasses. Both instance methods and class methods can access these shared variables.

A class variable is declared in the class definition template. For example, the class `Color` defines a large number of class variables to speed up color creation; its definition is shown below.

```ruby
Object subclass: #Color
    instanceVariableNames: 'rgb cachedDepth cachedBitPattern alpha'
    classVariableNames: 'BlueShift CacheColormaps ColorRegistry
                         ComponentMask GrayToIndexMap GreenShift HalfComponentMask
```
IndexedColors
MaskingMap RandomStream RedShift'
package: 'Graphics-Primitives'

The class variable ColorRegistry is an instance of IdentityDictionary containing the frequently-used colors, referenced by name. This dictionary is shared by all the instances of Color, as well as the class itself. It is accessible from all the instance and class methods.

## Class initialization

The presence of class variables raises the question: how do we initialize them?

One solution is lazy initialization (discussed earlier in this chapter). This can be done by introducing an accessor method which, when executed, initializes the variable if it has not yet been initialized. This implies that we must use the accessor all the time and never use the class variable directly. This furthermore imposes the cost of the accessor send and the initialization test. It also arguably defeats the point of using a class variable, since in fact it is no longer shared.

Another solution is to override the class method initialize (we've seen this before in the Dog example).

```color-class
Color class >> initialize
    ...
    self initializeColorRegistry.
    ...
```

If you adopt this solution, you will need to remember to invoke the `initialize` method after you define it (by evaluating `Color initialize`). Although class side `initialize` methods are executed automatically when code is loaded into memory (from a Monticello repository, for example), they are not executed automatically when they are first typed into the browser and compiled, or when they are edited and re-compiled.

## Pool variables

Pool variables are variables that are shared between several classes that may not be related by inheritance. Pool variables were originally stored in pool dictionaries; now they should be defined as class variables of dedicated classes (subclasses of SharedPool). Our advice is to avoid them; you will need them only in rare and specific circumstances. Our goal here is therefore to explain pool variables just enough so that you can understand them when you are reading code.

A class that accesses a pool variable must mention the pool in its class definition. For example, the class `Text` indicates that it is using the pool dictionary `TextConstants`, which contains all the text constants such as `CR` and `LF`. This
dictionary has a key `#CR` that is bound to the value `Character cr`, i.e., the carriage return character.

```
[ ArrayedCollection subclass: #Text
    instanceVariableNames: 'string runs'
    classVariableNames: ''
    poolDictionaries: 'TextConstants'
    package: 'Collections-Text'
]
```

This allows methods of the class `Text` to access the *keys* of the dictionary in the method body *directly*, i.e., by using variable syntax rather than an explicit dictionary lookup. For example, we can write the following method.

```
[ Text >> testCR
    ^ CR == Character cr
]
```

Once again, we recommend that you avoid the use of pool variables and pool dictionaries.

## 6.10 Internal object implementation note

Here is an implementation note for people that really want to go deep inside the way Pharo represents internally objects. The implementation distinguished between two different kinds of objects:

1. Objects with zero or more fields that are passed by reference and exist on the Pharo heap.

2. Immediate objects that are passed by value. Depending on version, these are a range of the integers called `SmallInteger`, all `Character` objects and possibly a sub-range of 64-bit floating-point numbers called `SmallFloat64`. In the implementation, such immediate objects occupy an object pointer, most of whose bits encode the immediate's value and some of the bits encode the object's class.

The first kind of object, an ordinary object, comes in a number of varieties:

1. Normal objects that have zero or more named instance variables, such as `Point` which has an `x` and a `y` instance variable. Each instance variable holds an object pointer, which can be a reference to another ordinary object or an immediate.

2. Indexable objects like arrays that have zero or more indexed instance variables numbered from 1 to N. Each indexed instance variable holds an object pointer, which can be a reference to another ordinary object or an immediate. Indexable objects are accessed using the messages `at:` and `at:put:`. For example `((Array new: 1) at: 1 put: 2; at: 1)` answers 2.