Smalltalk Basic Skills – Creating New Classes and Methods

I generally assume that readers of this blog will have basic Smalltalk skills (that is, are able to at least create and edit Smalltalk code). But just in case you’re coming in from the outside, and have no experience with any kind of Smalltalk, I would like to help walk you through some of the basics.
If you find this post helpful, leave a comment, so I know to post similar walkthroughs in the future.

Main Concept – Separate Class and Method Definitions

A quick note before we start. In other programming environments, the basic unit of code is a file. Whether you’re coding in Java, PHP or Ruby, and whether you’re using Emacs, vim, TextMate or Eclipse, the process is very similar. You create a new file in your code editor window, and start typing Class and Method (function) definitions. Everything important happens in the file, in the single code window. You have other list views and panes – there’s often a section of your text editor that lists all the files you’re working on, in your project. Many IDEs and code editors also have panes that list Classes and Functions defined in a particular file. Clicking on a class or function usually jumps you to their definition in the file – these list panes are aids to navigation. But in general, package/module declarations, Class definitions and Method definitions all live in the same file.

Smalltalk (especially in modern Smalltalk environments like VisualWorks, Squeak and Pharo), separates these definitions out, each to their own little window. The Class definition gets its own window, class comments and documentation (similar to JavaDoc blocks) gets its own, and each individual method is shown separately. If this sounds confusing, or slow to work with, do not worry. The Smalltalk IDE is built for this from the ground up. In practice, once you get used to finding your way around, navigating between different classes and methods is incredibly fast, often faster than in any other coding environment.

How to Create Your First Class

Ok, let’s get to it! Open your Seaside One-click Image. That window in the middle, titled WACounter? That’s the code/system browser. If you close it by accident, you can always either press Meta-B (that’s Alt-B on windows) or click on anywhere on the background in the Pharo window and select System Browser off the World Menu.

The leftmost pane of the System Browser should be a list of categories, containing entries like Seaside-Examples-Misc. Categories are ways to group code into conceptual areas, a way to divide code into projects or applications. They are the philosophical equivalent of Packages in other programming languages.

Let’s create a Category to house our first class. Right-click on the Packages pane, and select Add category. Enter something like Tutorials-Zen in the text window that pops up, and press Enter. That category gets created and highlighted – in the bottom code pane, you will now see the following:

Object subclass: #NameOfSubclass
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'Tutorials-Zen'

This is, essentially, the ‘Create a New Class’ interface. You can just start typing over the sample template text displayed there, and hit Meta-S to Save.

So, let’s create a class called MyFirstClass – highlight the word NameOfSubclass and type over it. This is what your code should look like, before you save:

Object subclass: #MyFirstClass
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'Tutorials-Zen'

When you hit Meta-S, you will see the class appear in the second pane on the top.

Side Question: What happpens when I create a class without a category? Nothing much – the class gets created with a blank category. The blank category gets listed as a blank line in the Package/Category list pane, at the bottom. And now your class is harder to find. So don’t do it.

Next step: let’s create a method in our new class. So far, you’ve used two panes on the top half of the System browser. The first (leftmost) one is the Packages/Categories pane. The second one is a pane listing Classes. The third one lists method categories (also called Protocols), which is an optional way to conceptually group methods within a class. We’re going to ignore these for now, and just use the default ‘–all–‘ method category.

So, click on MyFirstClass class to highlight it. Then click on the --all-- category in the next pane (to show that you want this new method to be in the default category). The ‘new method’ code template will appear, already highlighted (making it easier for you to delete it, and start writing your own code):

messageSelectorAndArgumentNames
	"comment stating purpose of message"

	| temporary variable names |
	statements

Delete all of that sample code, and type in your own (and hit Meta-S to save). Here’s the code for a simple method that returns a string:

myFirstMethod
	"My very first method. Simply returns a literal string."

	^'Hi there!'.

Once again, after you type the code and hit Meta-S to save, the method appears in the rightmost pane of the System browser.

Question: When I hit Meta-S for the first time, a popup window prompts me for my name! What is this?
Answer: Ah, this is the system prompting you for your name or intials, so it can know who edited what code. You know how most version control systems (CVS, Subversion, Git, what have you) keep track of user names, so you can figure out who made what change to a file? This is similar. Squeak/Pharo keeps track of the revision history for each method, and it prompts you for your name the first time you change anything during a coding session.

Finally, let’s add a second method to MyFirstClass. Again, click on the ‘--all--‘ method category, highlight the sample method template, and start typing:

mySecondMethod
	"A second method of my very own"

	| aTempVariable |
	aTempVariable := 1.
	^aTempVariable.

That’s it! Now you know how to create categories, classes and methods in Smalltalk.

“Setting It Up Right” – Loading Useful Extensions into Pharo

Table of Contents:

Ok, so this section turns out to be much shorter than I expected. I mostly wanted to write about installing OmniBrowser, which is an extension/rewrite of the system-provided code editors in Squeak/Pharo. It adds all sorts of nifty icons and helpful behaviors (such as right-click on a method and be able to see its Senders and Implementors), and is a great package. And I wanted to point out that it’s kind of indispensable (at least I found it so), which is I why I would want to side-track a simple Hello World tutorial with the explanation of how to install it.

However, it turns out that OmniBrowser already comes pre-installed on the Seaside One Click Pharo image. And my adventures in trying to install it come from plain Squeak, of several years ago.

Same thing with code code coloring/syntax highlighting, and code auto-completion – installed out of the box (again, I used to have to install it manually).

With the time we saved not setting things up, it’s time to actually start learning Smalltalk syntax. For those few who are actually learning Smalltalk (or refreshing their memories after a long absense), I highly recommend diving right into the excellent free online book, Pharo By Example, and taking it from page 1.

Next up, a simple Seaside Hello World running on your desktop.

Deployed Hello World – Installing Seaside and Squeak/Pharo Basics

Table of Contents:

Time to install Seaside. If you go to Seaside Download page (and click on the Seaside for Pharo Download link), you’ll see that there are several options. The easiest one is the Seaside One-click Experience — as I mentioned in the last post, this comes with a VM for your operating system, sources, and an image that comes with Seaside installed, and a web server started and ready to go as soon as you open up Pharo. This is the option you should go with — click on the latest one (at the time of this writing, it’s Seaside One-Click Experience 3.0.3).

Where should I unzip the download file? Squeak/Pharo is self-contained, so it doesn’t matter where you install it, it’s not going to make any Windows Registry entries or anything like that. I usually place it in C:\Pharo on Windows, or in my user directory on Linux.

To Launch Seaside: (after unzipping it into a Pharo folder) click on the folder, then on Seaside.app, then on Contents, then on the folder appropriate to your operating system, then on the executable.

If the VM is in Contents\Windows\, where is the image that I’ll be launching? The image lives in Contents\Resources. The default one that launches when you double-click on the executable is Contents\Resources\Seaside.image.

Go ahead and double-click on the executable and open Pharo. (On Windows, you will likely be prompted by the OS to permit the application to open a port — that’s the web server starting up). You will see three things — a server control panel, conveniently started for you, a code browser window, and what looks like a text file but is actually a full-fledged Workspace in which you can execute code (more on those later).

Where is the menu bar? File, Edit, Windows, Help, etc? Squeak/Pharo does not have the traditional menu bar running across the top that you see on most applications on Windows, Linux or Mac. It’s kind of like Emacs in that it tries to be its own universe (although even Emacs has menu bars on most latest versions). However, what you do have is the World Menu — click on any empty spot within the Squeak window (the squeak “desktop”, if you will), that is, anywhere not on the code browser or workspace, and you will see a popup menu titled “World”. This is essentially your menu bar, and contains the items you’d expect, Help and Windows commands, preferences, and so on.

Now the vi/Emacs question – how do I save and exit? Easy enough – click on an empty space on the Squeak desktop to bring up the World Menu >, then Save or Save and quit.

Wait, if I hit World Menu > Save, and then World Menu > Quit, why does it ask me if I want to exit without saving? Didn’t I just save? Yes, you did just save, so everything’s ok. It’s just being extra paranoid. If this disturbs you, then use the ‘Save and quit’ option to do both in one step, and then it won’t prompt you with that question.

When I click on the X icon to Close Window and exit, why does the prompt say ‘Quit Croquet without saving’, instead of Quit Pharo? That’s minor bug in the current release that I’m sure is left over from merging some of the code from Croquet into Pharo, ignore it. Actually, the Croquet Project is a fascinating VR/realtime collaboration project that’s implemented in Squeak, and is worth checking out.

OK, so how do I edit code? The last basic thing you need to know is how to actually edit code from within Pharo. Click over to the code browser window (it’ll say WACounter on the title bar — that’s the name of the class it’s browsing). Now click anywhere on the code and add an extra space or a return somewhere, just to have edited it. (Btw, see how the upper right corner of the code window turns orange? That’s how you know this method has been modified). Now, to save edited code, press Alt-S (I think it’s Cmd-S on Mac). (Why does Squeak use Alt-S instead of the more traditional Ctrl-S to save a window/buffer? I’m not entirely sure, but you can change this behavior in preferences (switch how Squeak handles Alt and Ctrl keys) to be more familiar for Windows/Linux users — I’ll explain how in the next post).

When you hit Alt-S (Squeak documentation will refer to this as Meta-S (Emacs users will find this familiar), so as to be consistent across operating systems), an Information Required prompt will pop up and ask for your name. Why does it do this? Because all code edits get saved in a version log (you can see this by clicking on the Versions button above the code editing area), and entering your name allows you to identify the code edits as yours. (When you start using source control tools like Monticello, this name will be used to sign your code changes). Think of it as the @author tag in the JavaDoc tool.

Important note: Meta-S just saves the code changes to a single method within the live image, it does not save the image itself. You still have to go World Menu > Save to save the whole image to disk, before you exit (or commit your changes to a version control system, once you start using one).

How do I open another code browser window? Go to World Menu > System Browser and that opens up a code browser window (incidentally, you can switch between the open windows in Squeak by pressing Meta-Left or Meta-Right keys, kind of like switching tabs in Eclipse or Firefox).

Ok, you now know enough to be dangerous to write code. Next up, a quick note on customization, and the on to the Hello World web app in Seaside.

Deployed Hello World – Basic Smalltalk Dev Environment Concepts

Table of Contents:

Before we install Seaside, I’d like to explain some terminology.

For example, if you go to the Pharo Download Page (though that’s not the one we’ll be ultimately using for this tutorial — we’ll use the Seaside Download Page instead), you’ll see several headings – “One-Click Image”, “Custom Downloads” with subheadings of “Image”, “Source Files” and “Virtual Machines”. What are all of these? First, let’s discuss some key concepts that you will be working with in the Smalltalk world.

Key Concepts

Virtual Machine

If you’re coming from the Java world, this is the Runtime Environment. It’s a small virtual machine, specific to your operating system, that runs Smalltalk bytecode. Hence, in the “Custom Downloads > Virtual Machines” section, you’ll see binaries for Windows, OS X and Unix.

Which VM should I use, Cog VM or “standard”? Don’t worry about it for now. Use Cog, which is a new JIT VM that promises to be faster than the standard one.

Images

If the Virtual Machine is the Runtime Environment, the Images are Eclipse (or a similar IDE), your workspace (with saved preferences and windows positions) and the code you’re working on.

Let me repeat that: The Image is the IDE, your workspace AND the code that you’ll be working on.

The Image is OS-independent. (Hence why there’s only one link, say, Pharo 1.1.1. image (stable) – use this for all operating systems). That means you can develop your code on Windows, then switch over to Linux, load up the image into the VM, and continue coding exactly where you left off, down to the placement of the code editor windows on the screen.

The image is also the unit of deployment. (Again, with the Java metaphor, think of it as the .jar file, that you’ll be rolling out to the server).

Wait, if I’m deploying the image, and the image also contains the IDE and workspace, does this mean my deployed app will contain all sorts of extra cruft? Good question. No, it will not — when preparing an image for deployment, you strip away all that non-essential code. So fear not.

Why is it all integrated like that (the IDE, workspace and code)? For various historical reasons I’m still fuzzy on, and which don’t really matter in this tutorial. However, the thing to take away is this: the tight integration is not going to hurt you, it will not create bloat (see the above), and it buys you some incredibly useful development and debugging capabilities.

What about collaboration? How do multiple developers work on one image? That’s where source control comes in. Though the Squeak/Pharo world does not use the usual source control tools (CVS, SVN, Git or Mercurial), it does use source control — Monticello, a “distributed, optimistic, concurrent, versioning system”, written in Smalltalk. (Again, the theme of tight integration, of Smalltalk all the way through, down to the support and development tools). Your day to day workflow will be roughly the same working in Monticello as with other source control tools, the same concepts apply — you’ll be updating your code to the latest revision, working on it, then committing, merging with that of other developers, etc.

PharoCore images

Ignore these. These are minimalist images for advanced users and core developers of the Pharo project itself.

Source files

This is the source code to much of the Virtual Machine, as well as some libraries and core classes. (In Debian/Ubuntu world, think of this as the source packages, to go with the binaries.)
The virtual machine will still work without source files, but when you click on some of the base classes, you’ll just see bytecode, and that’s not very useful.
You’ll want source files in your environment — part of the beauty of Smalltalk is that the source for the entire stack is available for your perusal.

.changes files

Though these are not referenced on the Download page, in various Smalltalk tutorials, you’ll hear mentions of change files, as in “copy your image and .changes file to your backup directory…”. You know how some database systems keep a transaction log, so that when the db server crashes, you can still recover all of the transactions from disk? This is what the .changes file is. It’s a log of all of your actions in the workspace, so that if your image crashes or becomes corrupted, you can still recover your code and data.

How often will it crash / will I have to use the .changes file? I’ve been developing in Smalltalk for 9 years, and I haven’t had to use it yet. That doesn’t mean you won’t have to, so I just wanted to mention it.

Putting It All Together – Windows Installer, and the “one-click image”

Now that you understand the basic components of a Smalltalk dev environment, those download links help you put it all together.

The Windows installer packages together a Windows VM, a starting image, and a sources file to go with it. If you’re developing on windows, just use this.

The Pharo x.x.x one-click image is a similar packaging, except it contains VMs for all 3 OSs (Windows, Linux and OS X), as well as an image and sources to go with them. So the idea is, you just download that one distribution, and then use whichever runtime your OS requires.

Finally, the Seaside 3.0 one-click experience on the Seaside Download Page is a zip file containing all 3 OS-specific VMs, sources, and an image file with the Seaside project already loaded into it, and the web server started. This is the one we’ll be using for our Deployed Hello World.

A Remote Server “Deployed Hello World” with Squeak/Pharo, Seaside and Ubuntu Linux

There are several excellent Squeak and Seaside “Hello World” tutorials out there, that walk you through downloading the Squeak Smalltalk environment, loading the Seaside web framework, and doing a basic “Hello World” web app on your web browser, running in localhost. Here are some of my favorites:

Now, what if you’re ready to take the next step? What if you’ve written a web application in Seaside, and would like to push a beta version out there, for the world to see? How do you get your Seaside app onto a remote server, and responding to an actual request to http://www.yourhelloworld.com?

In the next series of posts, I will walk you through the steps required to roll your code to your remote server. This is by no means a battle-hardened production ready deployment process. I’ve pieced this together from various scattered documentation, and through trial and error, and hopefully it will save you some minutes of research and some frustration.

Table of Contents:

Stay Tuned!

Why Smalltalk?

A quick word on why I choose to code in Smalltalk in my spare time, and why I enjoyed the hell out of working with it full-time, several jobs ago.

To put it simply, there is a feeling of delight, wonder and power when coding in a good Smalltalk environment (such as Squeak/Pharo or VisualWorks) that is unmatched by any other environment and IDE.

Like tasting fruit from the Goblin Market in the poem, and then forever pining away for it, working in Smalltalk spoils you for other languages (I’ve worked in C++, Java, Perl, Python, Ruby and Lisp) and development environments (tried VisualStudio, Eclipse, Emacs, vim, TextMate).

The two things that you spend most of your time doing as a programmer — coding and debugging — are made noticeably easier and more fun by that combination of Smalltalk language and IDE. The language syntax is small, powerful, expressive, introspective. The entire stack (and libraries, and IDE) is written in Smalltalk (turtles all the way down), and you have access to the source code, allowing you to study and extend all operations, basic and complex. The code organization — explicit, first-class visual IDE support for packages, classes, protocols (groupings of methods by intended use) and methods — is extremely helpful.

The debugger… is a thing of deep beauty. The ability, while, say, developing a web app, to not only set breakpoints and examine the state of the running program (even, if you set it up right, through the web browser itself — remind me to tell you about “halos”), but to be able to interact with the objects on the execution stack dynamically (i.e. call methods on them, and examine their output), and also to change code and resume execution from mid-halt… is freeing beyond belief.

The above things, by themselves, would merely make me like the language a lot, and miss its convenience. But the thing that makes it truly indispensable for me is Seaside, a web framework.

It is unorthodox, flexible, powerful, and… difficult to describe. I’m going to let people much more eloquent than me attempt to do so:
* Secrets of lightweight dev success, Part 8: Seaside
* A SeaSide Vacation

What’s the downside of working with Smalltalk, though? (Just ask the Lispers what the downside of working with Lisp is), rather than, say, in other sufficiently elegant and pleasant languages such as Ruby or Python?

In short, less popularity and a smaller developer base. Which means less third-party libraries, tools and open source projects. So, you’re a bit out there on the bleeding edge (which is funny, because Smalltalk is 30+ years old, but again, ask the Lispers about that).

The upshot, then is this. If you’re working on a well understood and often-solved problem (for example, CRUD-type record maintenance over the web), use something like Rails, Django or web2py. But, as is just as often the case, if your project is way off the beaten path (like, say, a web mud), Smalltalk and Seaside just might be perfect for you. And in any case, it is worth trying out for a week or a year. You will learn a hell of a lot.

Which Smalltalk?

[Edit: Updated February 2014]

When starting any project, a developer has to navigate a tree of choices. Which programming language do I choose? Which distribution? Which editor or IDE should I use with it? Which operating system should I target? Sometimes, the decision is easy since the environment is dictated by management: we’re a C# shop, so fire up VisualStudio on Windows and go. Or, we’re using Ruby, so pick your favorite code editor (TextMate, vim, Emacs, Eclipse) and you’re off, since you’re limited to pretty much one official Ruby distribution. Same with Python, or Perl — pick an editor and your favorite *nix OS (Windows support is more shaky for all these scripting languages), and you’re set. Sure, there are often experimental or alternate VMs and interpreters, but the mainstream production choice is clear.

Not so with Smalltalk. Much like with Lisp, a casual user first approaching the Smalltalk world is faced with a bewildering variety of Smalltalk versions. Which distribution and virtual machine (and therefore a slightly incompatible dialect and set of libraries) should you choose?

Fortunately, a bit of research narrows down the choices. Especially if you want to use the Seaside web development framework. Your options are:

Commercial Smalltalk Vendors

Open Source Smalltalk Projects

  • Squeak Smalltalk
  • Pharo (forked from Squeak in 2008, to take the project in a more Enterprise direction, and still under very active development)

Let’s run down the choices that I made in starting this project.

Q: Which programming language? A: Smalltalk
I have worked with Smalltalk for over 9 years, both as my day job (writing desktop applications in Visual Smalltalk and Cincom’s VisualWorks), and as a hobby (exploring Squeak Smalltalk). Though I have also worked on commercial projects using Java, Perl, PHP, Python and Ruby/Rails, I have not found anything in those worlds resembling Smalltalk’s powerful IDE and ease of debugging. Though the other languages enjoy a wider base of developers, open source projects, and third-party library support, the experience of working with Smalltalk (and Seaside) is profound, freeing and satisfying.

Q: Which Smalltalk? A: Pharo Smalltalk
Although the GLASS platform intrigues me, I don’t have much experience with it. And, given a choice, I always prefer to work with open-source technology rather than commercial distributions, hence the choice of Pharo (which I feel has more long-term longevity and openness) over VisualWorks (even though that has better commercial support, I don’t want to deal with license fees at this stage in the project).

So why Pharo and not Squeak? Although I’ve worked with “plain Squeak” for a number of years, the Pharo fork seemed like a reasonable choice, since it was chosen to be the reference implementation for the Seaside platform (perfect, exactly what I need it for). While I originally made this choice around 2009, having watched the Pharo community grow and blossom over the years, I do feel that currently (as of 2014) Pharo is the overwhelmingly correct choice (for web development).

Edit: The original reasons that I posted for choosing Pharo were:

a) removing unessential code from Squeak (Squeak, having started as a children’s education project, has accumulated a fair amount of cruft over the years), b) clearer licensing (MIT license), c) more frequent updates (think Ubuntu versus Debian), and d) being a reference implementation for the Seaside platform (perfect, exactly what I need it for).

However, as this thread on Pharo-Project mailing list pointed out, most of them are incorrect. My apologies for misunderstanding — I got those reasons from the Pharo Wikipedia entry when I came across the Pharo fork, and was trying to figure out whether to switch or not.

Q: Which version of Pharo? A: Pharo 2.0 (with testing on 3.0)
As of Feb 2014, Pharo 2.0 is the “current/stable” version, and 3.0 is undergoing active development. So far, I have not seen too many problems with interoperability, so I generally develop on 2.0, and make sure the tests pass on 3.0.

Q: Which IDE? A: Pharo
Unlike most programming languages, the code editor and IDE is often built into the distribution/VM (though the IDE code can be stripped out when getting a VM image ready for deployment). This may sound strange, but it buys you incredible debugging and refactoring powers. Like in Lisp, both the source code and the (on-the-fly) compiled methods and classes are first-class objects, so with a single keystroke, you can do things like “Show me a list of all the methods called from this method” or “Give me a list of all the other places in the code this function is called from” — something that has to be approximated with full-text searches in other IDEs and environments.

Q: Which operating system? A: Doesn’t matter, actually
Most of the main Smalltalk distributions are cross-platform, with the virtual machine and IDE working almost identically on Windows, Linux and MacOS X. Currently, I do development on Mac OS X or Ubuntu Linux (depending on which machine I’m working on), and deploy to a web server running Ubuntu.

I hope this sheds some light on this very individual set of decisions. One last thing I’d like to reiterate: If you’re new to Smalltalk and Seaside, you essentially can’t go wrong with the main distributions (VisualWorks, VA Smalltalk, GLASS or Pharo). All are excellent cross-platform environments, and the choice between them comes down to commercial support, licensing fees (and, in the case of Gemstone, whether or not you need a first class object-oriented database).

Welcome – Seaside Thoughts and Tutorials

Welcome. Over the course of this blog, I would like to share my thoughts and experiences on web development on the Seaside framework using the Smalltalk programming language.

My current project is to implement a Web MUD (an excellent example of this genre is Kingdom of Loathing), a text-based persistent online game with a web interface, using Riak as a persistence engine. But specifically, this blog focuses on general areas of interest to current Seaside users, and those interested in learning more about this amazing and flexible framework.