TweetFollow Us on Twitter

Learning Smalltalk
Volume Number:10
Issue Number:10
Column Tag:Smalltalk

Learning Smalltalk by Examples

Smalltalk - coming of age and offering an alternative to C and C++

By R. L. Peskin and S. S. Walther, Landgrove Associates, Flemington, New Jersey

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

This is the first in a series of articles aimed at those who want to learn something about programming in Smalltalk. Our overall objective is to convey the ease and flexibility of Smalltalk programming to those who may be used to programming in more traditional languages and environments. The approach will be practical; learning by example. We will be using the SmalltalkAgents™ system as the vehicle to illustrate our examples.

The Wire Project

The Wire example is a simple tool to determine the shortest length of wire running between an arbitrarily selected set of points. (If you aren’t into wire routing, the same sort of analysis applies to routing a salesperson between cities.) Kent Beck and Ward Cunningham first introduced us to this example at the Tektronix, Inc. Smalltalk classes in 1986. The Wire Project is a good illustration of “tool” building in Smalltalk; that is, integrating the behavior of a Model and the user interface to interact with that Model. The Model refers to your data, perhaps including the computations that generate them. The View is the interface to that data. Commonly this means a visual interface (list, graph, visualization), but it may well include sound, touch, smell, etc. in future platforms. The Controller refers to the set of messages and/or events that facilitate communication and control between the Model and View(s). Our Model is a list of Wire coordinates (list of points), together with the methods (behaviors) that do calculations relevant to those Wire coordinates. Our View is a dynamically changing graphical representation of the Wire points and the lines connecting them. Our Controller is not a formal object, but rather a group of behaviors that effect control; some of these are behaviors of the View and some of the Model.

The Wire tool accepts an arbitrary point from the user’s click in a window. The length of the Wire is computed and displayed as points are added. When the user clicks a “Shorten” button, the Wire rearranges its points to minimize the total length and the new arrangement is shown in the window. Here is a diagram of the Wire tool. We’ll focus on the implementation of the Model (WireList).

Wire Tool Environment

Smalltalk Programming

Smalltalk consist of an “image” which holds objects and their behaviors and other data in the form of interpretable code, and a “virtual machine” which acts as an interpreter of code. (This is an much oversimplified description, but sufficient for present purposes.) Unlike interpreters of old, these virtual machines can run full-out.

The Smalltalk environment is a basic set of tools. It makes Smalltalk a much more productive language to work in than traditional static languages. These tools allow immediate feedback for testing and debugging, as well as incremental development and alteration of code. Changes to individual algorithms (methods) as well as whole classes are easily accomplished interactively. This is in marked contrast to static object-oriented languages such as C++. The Smalltalk environment’s tools include classes that are available for the your immediate use. In addition, browsers give you access to the source code for these classes. Debugging tools and text editing fields in browsers and editors let you do code entry, compilation, and execution almost anywhere. Getting from the development process to a standalone application can be done directly within Smalltalk’s environment.

The main idea in Smalltalk programming is to program from examples. The primary tool is the Browser, an interactive tool which gives you access to the Smalltalk system code. It also lets you modify code and add your own classes and methods. Here’s a Browser view.

A Smalltalk Browser

In the upper left hand corner is the class being browsed (Rectangle). The main text edit section shows the method being browsed (intersects:). Comments are in quotes. A typical Smalltalk programming statement is: new := Rectangle basicNew. The object (in this case the class Rectangle) is sent a message (basicNew), and the resulting object assigned to the variable, new. Smalltalk syntax refers to the “receiver” (Rectangle in the above example) and the message “selector” (basicNew). Also note the line: «SectRect(self:Ptr; rect:Ptr; new:Ptr):Boolean», this is how a Mac ToolBox call (or other external function) is made in SmalltalkAgents™ (STA). Smalltalk programming is done by editing new or existing methods in the Browser’s edit view and saving the edit; saving automatically invokes the compiler. The result is a new or changed method in your “image” with associated byte code (or other binary) representation.

The Category View shown at the bottom has four list views; Categories, Classes, Protocols, and Methods. Categories and Protocols are for reference and classification purposes only, they have no “programmatic” aspect; Categories group classes together and Protocols group methods. Classes list the classes in the Smalltalk class library (including any you have added) and Methods list the behaviors (methods) for the selected class.

How do we decide what are the objects? How do we decide which classes to subclass? These are common agonies in object-oriented programming. Frankly it may not make that much difference as long as the decisions are reasonable. (For example, a class for our Wires should probably not be a subclass of Rectangle; they have no common behavior.) Some useful rules are 1) If in doubt make your class a subclass of Object (the top level generic class); you can always relocate it later very easily. 2) Choose to subclass under a class (other than Object itself) only if there is a reason to do so. For example, a good reason is so that you can make use of existing methods (behaviors). 3) Don’t create a class that doesn’t have significant computational responsibilities; classes should have behaviors.

A class has a data structure that contains information (data) about its state. These data are objects called instance variables. A class also contains references to behaviors (methods) that let you change or simply read its instance variables. Typically an object is a concrete instantiation, that is, member of a class. An object is a specific instance of a class, and has its own set of instance variables. Sometimes classes have behavior and data sufficient to make them do concrete things on their own without instances. Normally a class functions as a template; an object belonging to that class has real values for the class data.

The Wire Model

Our wire is a collection of (geometric) points. One choice is to make the class associated with the Wire a subclass of one of the collection classes. We’ll choose to make it a subclass of List. An equally valid (and perhaps better) choice is to make Wire a subclass of Object, and then provide it with an instance variable which itself is a List. In the first case, the Wire will inherit all the behavior of a List; in the second case, the Wire’s list instance variable would be accessed when List behavior is needed. For simplicity, we’ll chose the former.

We create a subclass of List called “WireList”. This operation is usually done by filling in a template in the Browser. Below is the class browser view for WireList. The programmer supplies the name of the subclass as a symbol (#WireList); the superclass (#List), and a list of instance variable names #(first second). (We’ll ignore other information such as the paths (e.g. Environment@#List) for now.

WireList Browser

The category view shows three Protocols, accessing (adding point, relocating points, returning specific instance variables), calculating (computing wire length, shortening the wire), and drawing (supporting calculations for drawing the wire). (Note: You might decide that this last protocol is not appropriate for a List. You might want to create a new subclass for Wire directly under class Object, and have the list as an instance variable. The beauty of Smalltalk is that you can make these “relocations” easily as the program develops, a situation somewhat different than that in C++.)

Now let’s fill in the behavior in the first two protocols, starting with accessing. First we want to add points to our list. We’ll use the following notation: WireList>I>add: to express “WireList class, Instance method, add: aPoint”. (An instance method is a behavior for specific objects which are instances of a class; we’ll come back to class methods later.)

WireList > I> add:

The meaning of add: is that the message add with a parameter (aPoint) is sent to an object which is an instance WireList. The result is that a new point is added to the specific WireList object. The add: method shown here is sent to “super”; this starts the search for the implementation in WireList’s superclass, List, which has the add: method we need. WireList>I>add: is actually not needed, we include it for illustrative purposes. If WireList didn’t have a method, add:, the superclass would be tried automatically. If the method is not found there, the search continues until some class in the hierarchy either knew how to do add:, or we run out of classes to search and a failure message gets returned. It is instructive to use the Browser tools to see all the different implementations of add: found in the system. (List is an STA class; equivalents in other systems are classes like OrderedCollection.)

First and second are examples of “accessors” - methods to get instance variables. For example,

WireList > I> second

This translates to “send the message position: 1 (go to the first position in the list) to self”. Self is a reference to the object itself, in this case a specific WireList; self is equivalent to “this” in C++. The semicolon is shorthand for cascading messages. The message “next” to find the next element in the list is sent to the result of the position: 1 message. The result returned, indicated by “^”, is the second element in the list. Note that neither “first” nor “second” are actually needed in the Wire tool; they are there for testing purposes. It is good coding form to use accessor methods to get and set instance variables, rather than directly access data structures. The final method in this group does a simple exchange of two list elements.

WireList > I> exchange:and:

In this method, at:put: is a method of class Object. At: is an accessor method of class Object. Temporary variables (whose scope is limited to the method) are denoted by vertical bars, e.g. |temp1 temp2 temp3|. A period is used to denote the end of a statement, and := is the assignment operator. In creating the Wire tool, we figured out that we needed exchange:and: during development of one of the algorithms under the calculating protocol. Protocol groupings were done as a final step (more on this later).

At this point we can do some computation. We can create a new WireList, put some values in it, access the second element and exchange any two elements. Smalltalk’s analog to the “terminal” is a Console or Transcript window. You can also open a window called a “workspace” and do line by line computing. In fact, you can do this in any appropriate code edit field of a Smalltalk window, including the code edit field of the Browser.

A Console Window

We’ll show you how some of this interactive stuff works. In the first line of the Console window, we created a new instance (member) of class WireList. new is a “constructor” method and is an example of a class method; all classes know how to respond to new to create new instances. In the second Console line, we added some points, and the next line shows the list of points returned. Then we asked Q for its second member, and 5@6 was returned. Finally we exchanged the 2nd and 3rd elements, and the resulting new list is shown. (Code in a Console can be executed line-by-line or grouped; once a selection is made, you can issue some sort of “execute” or “doIt” command.)

We are now ready to develop the calculating protocols, that is, the algorithms to shorten the Wire by seeking the minimum length connecting its points. We’ll do this by exchanging point positions in the list until we get a minimum length. Right away, we know we’ll need a method to compute distance between points. (This sort of functionality is supplied as one of the methods in class Point in some Smalltalk versions.)

WireList > I> distance: indx: to: p

This method differs from the usual class Point distance method; here we compute distance between a Wire’s point referenced via an index and some other point, p. (For simplicity, error checking is not included.) Next we’ll look at the method to compute the length of the Wire.

WireList > I> length

There is a lot in this method. After initializing the length to 0, the List>I>reset method is used to set the WireList pointer to the beginning of the list. Smalltalk ordered collections start their indexing at 1, so we set a temporary variable index, ‘previous’, to the first position. Next we encounter an iteration (do:) over a block. Block contexts in Smalltalk are denoted by code contained inside brackets, [ ]. Blocks are a very important part of Smalltalk programming, and have no simple counterpart in C; the context of a Block is preserved even if evaluation is delayed. In the above code, the do: operation iterates over all elements in the list. The syntax [:p | ....code...] denotes that p is a temporary object that will take on different values, the do: assigns p to the points in the list starting at the beginning. Inside the block, we use the method distance to compute the total length, which is returned at the end of the iteration.

The real action algorithmically in the Wire tool is contained in the method, shorten. This is not the appropriate place to discuss the algorithmics employed. It is sufficient that a simplified form of “simulated annealing” is used. We randomly pick integers from the WireList indices and interchange them and check to see if the interchange shortens the Wire.

WireList > I> shorten

This method has some new features. 100 timesRepeat: [...] does the code in the outer block 100 times. self size is the size of the Wire list. Float random is how random numbers are generated in STA; other systems may use different methods for this. Note the use of length and exchange:and: that were previously developed. self length < minLength returns a Boolean. ifTrue:[] ifFalse:[] is a Smalltalk conditional test; if the Boolean is true, one code block is performed, else another code block is performed.

Now we can test out these new methods in a Console window.

In the first line, a new WireList is created. (Smalltalk code is shown in bold; results are in plain.) Next its distance from the first element to the last point is computed; then the length is calculated. The Wire is told to shorten itself, and a new list results; in this simple case only the last two elements were interchanged. Finally the new length of the shortened wire is obtained. At this point in the development process, we have a fairly complete “model”. The next task is to create the tool per se so that the user can perform these operations on the model via mouse clicks and graphical viewing.

The Wire View and Control

We’ll have to leave a complete description of the Wire tool window (WireListWindow) and the control class (WireTool) to the next article, but here’s a quick overview. The steps are generally as follows:

First, we have to make a Window for the tool; in STA we create a subclass of a generic user interface window (UIWindow) which we call WireList Window. Usually this sort of thing is done with a GUI builder facility built into the Smalltalk system. Following is part of the window creation method, namely some code associated with the addition of a <shorten> button. The line ‘on: #buttonRelease send: #shorten to: self’ associates the event action (release of the Mouse button) with a method (shorten) that is sent to the WireListWindow when the Mouse is released.

Similar code sets up handling of Mouse action to add points to the Wire. A portion of the WireListWindow is shown below after the user has added some points:

The window looks as follows after pressing the “shorten” button two times (two iterations of the shorten algorithm):

Notice that the wire is shorter and the length has been reduced. How does the user action of clicking at points in the window result in a) drawing the wire, and b) adding said points to the Wire list? And how do we connect the pressing of the ‘shorten’ button in the window to invocation of the WireList > I> shorten method?

The answer to these questions rests on the fact that, in Smalltalk, views like the above WireListWindow maintain an instance variable (called module in STA) object which is assigned the model (in this case WireList) object instance. The point to be added is supplied by something like “p := Mouse localPosition”, which returns local window coordinates from the Mouse click. Code like “module add: p” adds a point to the list of the selected points. Pressing the ‘shorten’ button works the same way - the window’s shorten method simply asks the WireList to shorten; this invokes the wire shorten method we described previously.

How the actual drawing of the Wire is accomplished is an interesting point. The details are reasonably complex, and can be Smalltalk system dependent, but the programming is straightforward. When Smalltalk receives an update event, that update request is passed through to the WireListWindow, which handles it by invoking a rendering operation that includes the necessary call to draw the latest Wire based on the current contents of the WireList.

Conclusion

In this article we have tried to present an introduction to Smalltalk programming from a practical point of view. All of the code presented for the WireList can be used (with minor changes) in any Smalltalk version, including public domain ones. If a version of Smalltalk is available, we suggest typing in the WireList code and experimenting. The only way to get a feel for the simplicity and productivity of Smalltalk is to experiment with it. In the next article we will cover the programming support needed for the view and control process, as well as consider some additional tool features such as interactive point relocation and inspection tools.

For SmalltalkAgents™ users, the WireProject code can be found at ftp://qks.com/pub/sta/tutorials/WireList/. A text version of the WireProject suitable for implementation in other Smalltalk versions is available on request (email only) from R. Peskin. Internet: peskin@caip.rutgers.edu, Applelink: D6615, CompuServe: 70372,616. You can also get the project from the usual MacTech Magazine sites or source disk (see p. 2 for details).

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

LaunchBar 6.18.5 - Powerful file/URL/ema...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Affinity Designer 2.3.0 - Vector graphic...
Affinity Designer is an incredibly accurate vector illustrator that feels fast and at home in the hands of creative professionals. It intuitively combines rock solid and crisp vector art with... Read more
Affinity Photo 2.3.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
WhatsApp 23.24.78 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Adobe Photoshop 25.2 - Professional imag...
You can download Adobe Photoshop as a part of Creative Cloud for only $54.99/month Adobe Photoshop is a recognized classic of photo-enhancing software. It offers a broad spectrum of tools that can... Read more
PDFKey Pro 4.5.1 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Skype 8.109.0.209 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
OnyX 4.5.3 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
CrossOver 23.7.0 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more
Tower 10.2.1 - Version control with Git...
Tower is a Git client for OS X that makes using Git easy and more efficient. Users benefit from its elegant and comprehensive interface and a feature set that lets them enjoy the full power of Git.... Read more

Latest Forum Discussions

See All

Pour One Out for Black Friday – The Touc...
After taking Thanksgiving week off we’re back with another action-packed episode of The TouchArcade Show! Well, maybe not quite action-packed, but certainly discussion-packed! The topics might sound familiar to you: The new Steam Deck OLED, the... | Read more »
TouchArcade Game of the Week: ‘Hitman: B...
Nowadays, with where I’m at in my life with a family and plenty of responsibilities outside of gaming, I kind of appreciate the smaller-scale mobile games a bit more since more of my “serious" gaming is now done on a Steam Deck or Nintendo Switch.... | Read more »
SwitchArcade Round-Up: ‘Batman: Arkham T...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 1st, 2023. We’ve got a lot of big games hitting today, new DLC For Samba de Amigo, and this is probably going to be the last day this year with so many heavy hitters. I... | Read more »
Steam Deck Weekly: Tales of Arise Beyond...
Last week, there was a ton of Steam Deck coverage over here focused on the Steam Deck OLED. | Read more »
World of Tanks Blitz adds celebrity amba...
Wargaming is celebrating the season within World of Tanks Blitz with a new celebrity ambassador joining this year's Holiday Ops. In particular, British footballer and movie star Vinnie Jones will be brightening up the game with plenty of themed in-... | Read more »
KartRider Drift secures collaboration wi...
Nexon and Nitro Studios have kicked off the fifth Season of their platform racer, KartRider Dift, in quite a big way. As well as a bevvy of new tracks to take your skills to, and the new racing pass with its rewards, KartRider has also teamed up... | Read more »
‘SaGa Emerald Beyond’ From Square Enix G...
One of my most-anticipated releases of 2024 is Square Enix’s brand-new SaGa game which was announced during a Nintendo Direct. SaGa Emerald Beyond will launch next year for iOS, Android, Switch, Steam, PS5, and PS4 featuring 17 worlds that can be... | Read more »
Apple Arcade Weekly Round-Up: Updates fo...
This week, there is no new release for Apple Arcade, but many notable games have gotten updates ahead of next week’s holiday set of games. If you haven’t followed it, we are getting a brand-new 3D Sonic game exclusive to Apple Arcade on December... | Read more »
New ‘Honkai Star Rail’ Version 1.5 Phase...
The major Honkai Star Rail’s 1.5 update “The Crepuscule Zone" recently released on all platforms bringing in the Fyxestroll Garden new location in the Xianzhou Luofu which features many paranormal cases, players forming a ghost-hunting squad,... | Read more »
SwitchArcade Round-Up: ‘Arcadian Atlas’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for November 30th, 2023. It’s Thursday, and unlike last Thursday this is a regular-sized big-pants release day. If you like video games, and I have to believe you do, you’ll want to... | Read more »

Price Scanner via MacPrices.net

Deal Alert! Apple Smart Folio Keyboard for iP...
Apple iPad Smart Keyboard Folio prices are on Holiday sale for only $79 at Amazon, or 50% off MSRP: – iPad Smart Folio Keyboard for iPad (7th-9th gen)/iPad Air (3rd gen): $79 $79 (50%) off MSRP This... Read more
Apple Watch Series 9 models are now on Holida...
Walmart has Apple Watch Series 9 models now on Holiday sale for $70 off MSRP on their online store. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
Holiday sale this weekend at Xfinity Mobile:...
Switch to Xfinity Mobile (Mobile Virtual Network Operator..using Verizon’s network) and save $500 instantly on any iPhone 15, 14, or 13 and up to $800 off with eligible trade-in. The total is applied... Read more
13-inch M2 MacBook Airs with 512GB of storage...
Best Buy has the 13″ M2 MacBook Air with 512GB of storage on Holiday sale this weekend for $220 off MSRP on their online store. Sale price is $1179. Price valid for online orders only, in-store price... Read more
B&H Photo has Apple’s 14-inch M3/M3 Pro/M...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on Holiday sale this weekend for $100-$200 off MSRP, starting at only $1499. B&H offers free 1-2 day delivery to most... Read more
15-inch M2 MacBook Airs are $200 off MSRP on...
Best Buy has Apple 15″ MacBook Airs with M2 CPUs in stock and on Holiday sale for $200 off MSRP on their online store. Their prices are among the lowest currently available for new 15″ M2 MacBook... Read more
Get a 9th-generation Apple iPad for only $249...
Walmart has Apple’s 9th generation 10.2″ iPads on sale for $80 off MSRP on their online store as part of their Cyber Week Holiday sale, only $249. Their prices are the lowest new prices available for... Read more
Space Gray Apple AirPods Max headphones are o...
Amazon has Apple AirPods Max headphones in stock and on Holiday sale for $100 off MSRP. The sale price is valid for Space Gray at the time of this post. Shipping is free: – AirPods Max (Space Gray... Read more
Apple AirTags 4-Pack back on Holiday sale for...
Amazon has Apple AirTags 4 Pack back on Holiday sale for $79.99 including free shipping. That’s 19% ($20) off Apple’s MSRP. Their price is the lowest available for 4 Pack AirTags from any of the... Read more
New Holiday promo at Verizon: Buy one set of...
Looking for more than one set of Apple AirPods this Holiday shopping season? Verizon has a great deal for you. From today through December 31st, buy one set of AirPods on Verizon’s online store, and... Read more

Jobs Board

Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and offer a Read more
Senior Manager, Product Management - *Apple*...
…Responsibilities** We are seeking an ambitious, data-driven thinker to assist the Apple Product Development team as our Wireless Product division continues to grow Read more
Mobile Platform Engineer ( *Apple* /AirWatch)...
…systems, installing and maintaining certificates, navigating multiple network segments and Apple /IOS devices, Mobile Device Management systems such as AirWatch, and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.