Smalltalk

Last updated
Smalltalk
Smalltalk Balloon.svg
Paradigm Object-oriented
Designed by Alan Kay, Dan Ingalls, Adele Goldberg
Developer Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Diana Merry, Scott Wallace, Peter Deutsch and Xerox PARC
First appeared1972;52 years ago (1972) (development begun 1969)
Stable release
Smalltalk-80 version 2 / 1980;44 years ago (1980)
Typing discipline objects, but in some implementations, strong or dynamic
Scope Lexical (static)
Implementation languageSmalltalk
Platform Xerox Alto (74181) [1] [2]
OS Cross-platform (multi-platform)
Major implementations
Amber, Dolphin Smalltalk, GemStone/S, GNU Smalltalk, Pharo, Smalltalk/X, Squeak, Cuis Smalltalk, Haver, VA Smalltalk, VisualWorks
Influenced by
Lisp, [3] Simula, [3] Euler, [3] IMP, [3] Planner, [3] Logo, [4] Sketchpad, [3] ARPAnet, [3] Burroughs B5000 [3]
Influenced
AppleScript, Common Lisp Object System, Dart, Dylan, Erlang, Etoys, Go, Groovy, Io, Ioke, Java, Lasso, Logtalk, Newspeak, NewtonScript, Object REXX, Objective-C, PHP 5, Python, Raku, Ruby, Scala, Scratch, Self, Swift

Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learning Research Group (LRG) scientists, including Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Diana Merry, and Scott Wallace.

Contents

In Smalltalk, executing programs are built of opaque, atomic, so-called objects, which are instances of template code stored in classes. These objects intercommunicate by passing of messages, via an intermediary virtual machine environment (VM). A relatively small number of objects, called primitives, are not amenable to live redefinition, sometimes being defined independently of the Smalltalk programming environment.

Having undergone significant industry development toward other uses, including business and database functions, Smalltalk is still in use today. When first publicly released, Smalltalk-80 presented innovative and foundational ideas for the nascent field of object-oriented programming (OOP).

Since inception, the language provided interactive programming via an integrated development environment. This requires reflection and late binding in the language execution of code. Later development has led to at least one instance of Smalltalk execution environment which lacks such an integrated graphical user interface or front-end.

Smalltalk-like languages are in active development and have gathered loyal communities of users around them. American National Standards Institute (ANSI) Smalltalk was ratified in 1998 and represents the standard version of Smalltalk. [5]

Smalltalk took second place for "most loved programming language" in the Stack Overflow Developer Survey in 2017, [6] but it was not among the 26 most loved programming languages of the 2018 survey. [7]

History

There are a large number of Smalltalk variants. [8] The unqualified word Smalltalk is often used to indicate the Smalltalk-80 language and compatible VM, the first version to be made publicly available and created in 1980. The first hardware-environments which ran the Smalltalk VMs were Xerox Alto computers.

Smalltalk was the product of research led by Alan Kay at Xerox Palo Alto Research Center (PARC); Alan Kay designed most of the early Smalltalk versions, Adele Goldberg wrote most of the documentation, and Dan Ingalls implemented most of the early versions. The first version, termed Smalltalk-71, was created by Kay in a few mornings on a bet that a programming language based on the idea of message passing inspired by Simula could be implemented in "a page of code". [4] A later variant used for research work is now termed Smalltalk-72 and influenced the development of the Actor model. Its syntax and execution model were very different from modern Smalltalk variants.

After significant revisions which froze some aspects of execution semantics to gain performance (by adopting a Simula-like class inheritance model of execution), Smalltalk-76 was created. This system had a development environment featuring most of the now familiar tools, including a class library code browser/editor. Smalltalk-80 added metaclasses, to help maintain the "everything is an object" (except variables) paradigm by associating properties and behavior with individual classes, and even primitives such as integer and Boolean values (for example, to support different ways to create instances).

Smalltalk-80 was the first language variant made available outside of PARC. In 1981 it was shared with Tektronix, Hewlett-Packard, Apple Computer, and DEC for review and debugging on their platforms. [9] [10] The August 1981 issue of Byte Magazine was devoted to Smalltalk-80 and brought its ideas to a large audience. Several books on Smalltalk-80 were also published. Smalltalk-80 became the basis for all future commercial versions of Smalltalk. [11] The final release of Smalltalk-80 Version 1 was in November 1981. [12] Xerox only distributed Version 1 to Apple, DEC, HP, and Tektronix, but these companies were allowed unrestricted redistribution via any system they built. This encouraged the wide spread of Smalltalk. [13] Later, in 1983, Xerox released Smalltalk-80 Version 2. This version was generally available to the public, although under a restrictive license. Versions 1 and 2 were fairly similar, although Version 2 did have some added features such as a spelling corrector. Each release consisted of a virtual image (platform-independent file with object definitions) and a virtual machine specification. [13]

ANSI Smalltalk has been the standard language reference since 1998. [14] Two currently popular Smalltalk implementation variants are descendants of those original Smalltalk-80 images. Squeak is an open source implementation derived from Smalltalk-80 Version 1 by way of Apple Smalltalk. VisualWorks is derived from Smalltalk-80 version 2 by way of Smalltalk-80 2.5 and ObjectWorks (both products of ParcPlace Systems, a Xerox PARC spin-off company formed to bring Smalltalk to the market). As an interesting link between generations, in 2001, Vassili Bykov implemented Hobbes, a virtual machine running Smalltalk-80 inside VisualWorks. [15] (Dan Ingalls later ported Hobbes to Squeak.)

During the late 1980s to mid-1990s, Smalltalk environments, including support, training and add-ons, were sold by two competing organizations: ParcPlace Systems and Digitalk, both California based. ParcPlace Systems tended to focus on the Unix/Sun microsystems market, while Digitalk focused on Intel-based PCs running Microsoft Windows or IBM's OS/2. Both firms struggled to take Smalltalk mainstream due to Smalltalk's substantial memory needs, limited run-time performance, and initial lack of supported connectivity to SQL-based relational database servers. While the high price of ParcPlace Smalltalk limited its market penetration to mid-sized and large commercial organizations, the Digitalk products initially tried to reach a wider audience with a lower price. IBM initially supported the Digitalk product, but then entered the market with a Smalltalk product in 1995 named VisualAge/Smalltalk. Easel introduced Enfin at this time on Windows and OS/2. Enfin became far more popular in Europe, as IBM introduced it into IT shops before their development of IBM Smalltalk (later VisualAge). Enfin was later acquired by Cincom Systems, and is now sold under the name ObjectStudio, and is part of the Cincom Smalltalk product suite.

In 1995, ParcPlace and Digitalk merged into ParcPlace-Digitalk and then rebranded in 1997 as ObjectShare, located in Irvine, CA. ObjectShare (NASDAQ: OBJS) was traded publicly until 1999, when it was delisted and dissolved. The merged firm never managed to find an effective response to Java as to market positioning, and by 1997 its owners were looking to sell the business. In 1999, Seagull Software acquired the ObjectShare Java development lab (including the original Smalltalk/V and Visual Smalltalk development team), and still owns VisualSmalltalk, although worldwide distribution rights for the Smalltalk product remained with ObjectShare who then sold them to Cincom. [16] VisualWorks was sold to Cincom and is now part of Cincom Smalltalk. Cincom has backed Smalltalk strongly, releasing multiple new versions of VisualWorks and ObjectStudio each year since 1999.

Cincom, GemTalk, and Instantiations, continue to sell Smalltalk environments. IBM has 'end of life'd VisualAge Smalltalk having in the late 1990s decided to back Java instead and it is, as of 2005, supported by Instantiations, Inc. [17] who renamed the product VA Smalltalk (VAST Platform) and continue to release new versions yearly. The open Squeak implementation has an active community of developers, including many of the original Smalltalk community, and was used to provide the Etoys environment on the One Laptop per Child (OLPC) project, a toolkit for developing collaborative applications Croquet Project, and the Open Cobalt virtual world application. GNU Smalltalk is a free software implementation of a derivative of Smalltalk-80 from the GNU project. Pharo Smalltalk is a fork of Squeak oriented toward research and use in commercial environments.

As of 2016, a significant development that has spread across all Smalltalk environments is the increasing usage of two web frameworks, Seaside and AIDA/Web, to simplify the building of complex web applications. Seaside has seen considerable market interest with Cincom, Gemstone, and Instantiations incorporating and extending it.

Influences

Smalltalk was one of many object-oriented programming languages based on Simula. [18] Smalltalk is also one of the most influential programming languages. Virtually all of the object-oriented languages that came after—Flavors, [19] CLOS, Objective-C, Java, Python, Ruby, [20] and many others—were influenced by Smalltalk. Smalltalk was also one of the most popular languages for agile software development methods, rapid application development (RAD) or prototyping, and software design patterns. [21] The highly productive environment provided by Smalltalk platforms made them ideal for rapid, iterative development.

Smalltalk emerged from a larger program of Advanced Research Projects Agency (ARPA) funded research that in many ways defined the modern world of computing. In addition to Smalltalk, working prototypes of things such as hypertext, GUIs, multimedia, the mouse, telepresence, and the Internet were developed by ARPA researchers in the 1960s. [22] [23] Alan Kay (one of the inventors of Smalltalk) also described a tablet computer he named the Dynabook which resembles modern tablet computers like the iPad. [4]

Smalltalk environments were often the first to develop what are now common object-oriented software design patterns. One of the most popular is the model–view–controller (MVC) pattern for user interface design. The MVC pattern enables developers to have multiple consistent views of the same underlying data. It's ideal for software development environments, where there are various views (e.g., entity-relation, dataflow, object model, etc.) of the same underlying specification. Also, for simulations or games where the underlying model may be viewed from various angles and levels of abstraction. [24]

In addition to the MVC pattern, the Smalltalk language and environment were highly influential in the history of the graphical user interface (GUI) and the what you see is what you get (WYSIWYG) user interface, font editors, and desktop metaphors for UI design. The powerful built-in debugging and object inspection tools that came with Smalltalk environments set the standard for all the integrated development environments, starting with Lisp Machine environments, that came after. [25]

Object-oriented programming

Smalltalk-80: The Language and its Implementation, a.k.a. the "Blue book", an original book on the language Smalltalk80book.jpg
Smalltalk-80: The Language and its Implementation, a.k.a. the "Blue book", an original book on the language

As in other object-oriented languages, the central concept in Smalltalk-80 (but not in Smalltalk-72) is that of an object. An object is always an instance of a class. Classes are "blueprints" that describe the properties and behavior of their instances. For example, a GUI's window class might declare that windows have properties such as the label, the position and whether the window is visible or not. The class might also declare that instances support operations such as opening, closing, moving and hiding. Each particular window object would have its own values of those properties, and each of them would be able to perform operations defined by its class.

A Smalltalk object can do exactly three things:

  1. Hold state (references to other objects).
  2. Receive a message from itself or another object.
  3. In the course of processing a message, send messages to itself or another object.

The state an object holds is always private to that object. Other objects can query or change that state only by sending requests (messages) to the object to do so. Any message can be sent to any object: when a message is received, the receiver determines whether that message is appropriate. Alan Kay has commented that despite the attention given to objects, messaging is the most important concept in Smalltalk: "The big idea is 'messaging'—that is what the kernel of Smalltalk/Squeak is all about (and it's something that was never quite completed in our Xerox PARC phase)." [26]

Unlike most other languages, Smalltalk objects can be modified while the system is running. Live coding and applying fixes 'on-the-fly' is a dominant programming methodology for Smalltalk and is one of the main reasons for its efficiency.

Smalltalk is a "pure" object-oriented programming language, meaning that, unlike C++ and Java, there is no difference between values which are objects and values which are primitive types. In Smalltalk, primitive values such as integers, Booleans and characters are also objects, in the sense that they are instances of corresponding classes, and operations on them are invoked by sending messages. A programmer can change or extend (through subclassing) the classes that implement primitive values, so that new behavior can be defined for their instances—for example, to implement new control structures—or even so that their existing behavior will be changed. This fact is summarized in the commonly heard phrase "In Smalltalk everything is an object", which may be more accurately expressed as "all values are objects", as variables are not.

Since all values are objects, classes are also objects. Each class is an instance of the metaclass of that class. Metaclasses in turn are also objects, and are all instances of a class named Metaclass. Code blocks—Smalltalk's way of expressing anonymous functions—are also objects. [27]

Reflection

Reflection is a term that computer scientists apply to software programs that have the ability to inspect their own structure, for example their parse tree or data types of input and output parameters. Reflection is a feature of dynamic, interactive languages such as Smalltalk and Lisp. Interactive programs with reflection (either interpreted or compiled) maintain the state of all in-memory objects, including the code object itself, which are generated during parsing/compilation and are programmatically accessible and modifiable.

Reflection is also a feature of having a meta-model as Smalltalk does. The meta-model is the model that describes the language, and developers can use the meta-model to do things like walk through, examine, and modify the parse tree of an object, or find all the instances of a certain kind of structure (e.g., all instances of the Method class in the meta-model).

Smalltalk-80 is a totally reflective system. Smalltalk-80 provides both structural and computational reflection. Smalltalk is a structurally reflective system which structure is defined by Smalltalk-80 objects. The classes and methods that define the system are also objects and fully part of the system that they help define. The Smalltalk compiler compiles textual source code into method objects, typically instances of CompiledMethod. These get added to classes by storing them in a class's method dictionary. The part of the class hierarchy that defines classes can add new classes to the system. The system is extended by running Smalltalk-80 code that creates or defines classes and methods. In this way a Smalltalk-80 system is a "living" system, carrying around the ability to extend itself at run time.

Since the classes are objects, they can be asked questions such as "what methods do you implement?" or "what fields/slots/instance variables do you define?". So objects can easily be inspected, copied, (de)serialized and so on with generic code that applies to any object in the system. [28]

Smalltalk-80 also provides computational reflection, the ability to observe the computational state of the system. In languages derived from the original Smalltalk-80 the current activation of a method is accessible as an object named via a pseudo-variable (one of the six reserved words), thisContext. By sending messages to thisContext a method activation can ask questions like "who sent this message to me". These facilities make it possible to implement coroutines or Prolog-like back-tracking without modifying the virtual machine. The exception system is implemented using this facility. One of the more interesting uses of this is in the Seaside web framework which relieves the programmer of dealing with the complexity of a Web Browser's back button by storing continuations for each edited page and switching between them as the user navigates a web site. Programming the web server using Seaside can then be done using a more conventional programming style. [29]

An example of how Smalltalk can use reflection is the mechanism for handling errors. When an object is sent a message that it does not implement, the virtual machine sends the object the doesNotUnderstand: message with a reification of the message as an argument. The message (another object, an instance of Message) contains the selector of the message and an Array of its arguments. In an interactive Smalltalk system the default implementation of doesNotUnderstand: is one that opens an error window (a Notifier) reporting the error to the user. Through this and the reflective facilities the user can examine the context in which the error occurred, redefine the offending code, and continue, all within the system, using Smalltalk-80's reflective facilities. [30] [31]

By creating a class that understands (implements) only doesNotUnderstand:, one can create an instance that can intercept any message sent to it via its doesNotUnderstand: method. Such instances are called transparent proxies. [32] Such proxies can then be used to implement a number of facilities such as distributed Smalltalk where messages are exchanged between multiple Smalltalk systems, database interfaces where objects are transparently faulted out of a database, promises, etc. The design of distributed Smalltalk influenced such systems as CORBA.

Syntax

Smalltalk-80 syntax is rather minimalist, based on only a handful of declarations and reserved words. In fact, only six "keywords" are reserved in Smalltalk: true, false, nil, self, super, and thisContext. These are properly termed pseudo-variables, identifiers that follow the rules for variable identifiers but denote bindings that a programmer cannot change. The true, false, and nil pseudo-variables are singleton instances. self and super refer to the receiver of a message within a method activated in response to that message, but sends to super are looked up in the superclass of the method's defining class rather than the class of the receiver, which allows methods in subclasses to invoke methods of the same name in superclasses. thisContext refers to the current activation record. The only built-in language constructs are message sends, assignment, method return and literal syntax for some objects. From its origins as a language for children of all ages, standard Smalltalk syntax uses punctuation in a manner more like English than mainstream coding languages. The remainder of the language, including control structures for conditional evaluation and iteration, is implemented on top of the built-in constructs by the standard Smalltalk class library. (For performance reasons, implementations may recognize and treat as special some of those messages; however, this is only an optimization and is not coded into the language syntax.)

The adage that "Smalltalk syntax fits on a postcard" may have originated in Alan Kay's original conception of the language, as related by him in practically every of tens or hundreds of public lectures, op. cit., or perhaps it could refer to a code snippet by Ralph Johnson, demonstrating all the basic standard syntactic elements of methods: [33] [34]

exampleWithNumber:x| y |true&falsenot& (nilisNil) ifFalse: [selfhalt].y:=selfsize+supersize.#($a#a'a'11.0)do: [ :each|Transcriptshow: (eachclassname);show:' '].^x<y

Literals

The following examples illustrate the most common objects which can be written as literal values in Smalltalk-80 methods.

Numbers. The following list illustrates some of the possibilities.

42-42123.451.2345e22r1001001016rA000

The last two entries are a binary and a hexadecimal number, respectively. The number before the 'r' is the radix or base. The base does not have to be a power of two; for example 36rSMALLTALK is a valid number equal to 80738163270632 decimal.

Characters are written by preceding them with a dollar sign:

$A

Strings are sequences of characters enclosed in single quotes:

'Hello, world!'

To include a quote in a string, escape it using a second quote:

'I said, ''Hello, world!'' to them.'

Double quotes do not need escaping, since single quotes delimit a string:

'I said, "Hello, world!" to them.'

Two equal strings (strings are equal if they contain all the same characters) can be different objects residing in different places in memory. In addition to strings, Smalltalk has a class of character sequence objects named Symbol. Symbols are guaranteed to be unique—there can be no two equal symbols which are different objects. Because of that, symbols are very cheap to compare and are often used for language artifacts such as message selectors (see below).

Symbols are written as # followed by a string literal. For example:

#'foo'

If the sequence does not include whitespace or punctuation characters, this can also be written as:

#foo

Arrays:

#(1234)

defines an array of four integers.

Many implementations support the following literal syntax for ByteArrays:

#[1234] 

defines a ByteArray of four integers.

And last but not least, blocks (anonymous function literals)

[... Somesmalltalkcode...] 

Blocks are explained in detail further in the text.

Many Smalltalk dialects implement additional syntaxes for other objects, but the ones above are the essentials supported by all.

Variable declarations

The two kinds of variables commonly used in Smalltalk are instance variables and temporary variables. Other variables and related terminology depend on the particular implementation. For example, VisualWorks has class shared variables and namespace shared variables, while Squeak and many other implementations have class variables, pool variables and global variables.

Temporary variable declarations in Smalltalk are variables declared inside a method (see below). They are declared at the top of the method as names separated by spaces and enclosed by vertical bars. For example:

| index |

declares a temporary variable named index which contains initially the value nil.

Multiple variables may be declared within one set of bars:

| index vowels |

declares two variables: index and vowels. All variables are initialized. Variables are initialized to nil except the indexed variables of Strings, which are initialized to the null character or ByteArrays which are initialized to 0.

Assignment

A variable is assigned a value via the ':=' syntax. So:

vowels:='aeiou'

Assigns the string 'aeiou' to the formerly declared vowels variable. The string is an object (a sequence of characters between single quotes is the syntax for literal strings), created by the compiler at compile time.

In the original Parc Place image, the glyph of the underscore character ⟨_⟩ appeared as a left-facing arrow ⟨←⟩ (like in the 1963 version of the ASCII code). Smalltalk originally accepted this left-arrow as the only assignment operator. Some modern code still contains what appear to be underscores acting as assignments, hearkening back to this original usage. Most modern Smalltalk implementations accept either the underscore or the colon-equals syntax.

Messages

The message is the most fundamental language construct in Smalltalk. Even control structures are implemented as message sends. Smalltalk adopts by default a dynamic dispatch and single dispatch strategy (as opposed to multiple dispatch, used by some other object-oriented languages).

The following example sends the message 'factorial' to number 42:

42factorial

In this situation 42 is called the message receiver, while 'factorial' is the message selector. The receiver responds to the message by returning a value (presumably in this case the factorial of 42). Among other things, the result of the message can be assigned to a variable:

aRatherBigNumber:=42factorial

"factorial" above is what is called a unary message because only one object, the receiver, is involved. Messages can carry additional objects as arguments, as follows:

2raisedTo:4

In this expression two objects are involved: 2 as the receiver and 4 as the message argument. The message result, or in Smalltalk parlance, the answer is supposed to be 16. Such messages are called keyword messages. A message can have more arguments, using the following syntax:

'hello world'indexOf:$ostartingAt:6

which answers the index of character 'o' in the receiver string, starting the search from index 6. The selector of this message is "indexOf:startingAt:", consisting of two pieces, or keywords.

Such interleaving of keywords and arguments is meant to improve readability of code, since arguments are explained by their preceding keywords. For example, an expression to create a rectangle using a C++ or Java-like syntax might be written as:

newRectangle(100,200);

It's unclear which argument is which. By contrast, in Smalltalk, this code would be written as:

Rectanglewidth:100height:200

The receiver in this case is "Rectangle", a class, and the answer will be a new instance of the class with the specified width and height.

Finally, most of the special (non-alphabetic) characters can be used as what are called binary messages. These allow mathematical and logical operators to be written in their traditional form:

3+4

which sends the message "+" to the receiver 3 with 4 passed as the argument (the answer of which will be 7). Similarly,

3>4

is the message ">" sent to 3 with argument 4 (the answer of which will be false).

Notice, that the Smalltalk-80 language itself does not imply the meaning of those operators. The outcome of the above is only defined by how the receiver of the message (in this case a Number instance) responds to messages "+" and ">".

A side effect of this mechanism is operator overloading. A message ">" can also be understood by other objects, allowing the use of expressions of the form "a > b" to compare them.

Expressions

An expression can include multiple message sends. In this case expressions are parsed according to a simple order of precedence. Unary messages have the highest precedence, followed by binary messages, followed by keyword messages. For example:

3factorial+4factorialbetween:10and:100

is evaluated as follows:

  1. 3 receives the message "factorial" and answers 6
  2. 4 receives the message "factorial" and answers 24
  3. 6 receives the message "+" with 24 as the argument and answers 30
  4. 30 receives the message "between:and:" with 10 and 100 as arguments and answers true

The answer of the last message sent is the result of the entire expression.

Parentheses can alter the order of evaluation when needed. For example,

(3factorial+4) factorialbetween:10and:100

will change the meaning so that the expression first computes "3 factorial + 4" yielding 10. That 10 then receives the second "factorial" message, yielding 3628800. 3628800 then receives "between:and:", answering false.

Because the meaning of binary messages is not coded into Smalltalk-80 syntax, all of them are considered to have equal precedence and are evaluated simply from left to right. Because of this, the meaning of Smalltalk expressions using binary messages can be different from their "traditional" interpretation:

3+4*5

is evaluated as "(3 + 4) * 5", producing 35. To obtain the expected answer of 23, parentheses must be used to explicitly define the order of operations:

3+ (4*5) 

Unary messages can be chained by writing them one after another:

3factorialfactoriallog

which sends "factorial" to 3, then "factorial" to the result (6), then "log" to the result (720), producing the result 2.85733.

A series of expressions can be written as in the following (hypothetical) example, each separated by a period. This example first creates a new instance of class Window, stores it in a variable, and then sends two messages to it.

| window |window:=Windownew.windowlabel:'Hello'.windowopen

If a series of messages are sent to the same receiver as in the example above, they can also be written as a cascade with individual messages separated by semicolons:

Windownewlabel:'Hello';open

This rewrite of the earlier example as a single expression avoids the need to store the new window in a temporary variable. According to the usual precedence rules, the unary message "new" is sent first, and then "label:" and "open" are sent to the receiver of "new".

Code blocks

A block of code (an anonymous function) can be expressed as a literal value (which is an object, since all values are objects). This is achieved with square brackets:

[ :params|<message-expressions> ] 

Where :params is the list of parameters the code can take. This means that the Smalltalk code:

[:x|x+1] 

can be understood as:

or expressed in lambda terms as:

and

[:x|x+1] value:3

can be evaluated as

Or in lambda terms as:

The resulting block object can form a closure: it can access the variables of its enclosing lexical scopes at any time. Blocks are first-class objects.

Blocks can be executed by sending them the value message. Compound variations exist to provide parameters to the block e.g., value:value: and valueWithArguments:.

The literal representation of blocks was an innovation which on the one hand allowed certain code to be significantly more readable; it allowed algorithms involving iteration to be coded in a clear and concise way. Code that would typically be written with loops in some languages can be written concisely in Smalltalk using blocks, sometimes in a single line. But more importantly blocks allow control structure to be expressed using messages and polymorphism, since blocks defer computation and polymorphism can be used to select alternatives. So if-then-else in Smalltalk is written and implemented as

exprifTrue: [statementstoevaluateifexpr] ifFalse: [statementstoevaluateifnotexpr] 

True methods for evaluation

'''ifTrue:''' trueAlternativeBlock '''ifFalse:''' falseAlternativeBlock<br />      ^trueAlternativeBlock value

False methods for evaluation

'''ifTrue:''' trueAlternativeBlock '''ifFalse:''' falseAlternativeBlock<br />     ^falseAlternativeBlock value
positiveAmounts:=allAmountsselect: [:anAmount|anAmountisPositive] 

This is related to functional programming, wherein patterns of computation (here selection) are abstracted into higher-order functions. For example, the message select: on a Collection is equivalent to the higher-order function filter on an appropriate functor. [35]

Control structures

Control structures do not have special syntax in Smalltalk. They are instead implemented as messages sent to objects. For example, conditional execution is implemented by sending the message ifTrue: to a Boolean object, passing as an argument the block of code to be executed if and only if the Boolean receiver is true. The two subclasses of Boolean both implement ifTrue:, where the implementation in subclass True always evaluates the block and the implementation in subclass False never evaluates the block.

The following code demonstrates this:

result:=a>bifTrue:[ 'greater' ]     ifFalse:[ 'less or equal' ] 

Blocks are also used to implement user-defined control structures, enumerators, visitors, exception handling, pluggable behavior and many other patterns. For example:

| aString vowels |aString:='This is a string'.vowels:=aStringselect: [:aCharacter|aCharacterisVowel].

In the last line, the string is sent the message select: with an argument that is a code block literal. The code block literal will be used as a predicate function that should answer true if and only if an element of the String should be included in the Collection of characters that satisfy the test represented by the code block that is the argument to the "select:" message.

A String object responds to the "select:" message by iterating through its members (by sending itself the message "do:"), evaluating the selection block ("aBlock") once with each character it contains as the argument. When evaluated (by being sent the message "value: each"), the selection block (referenced by the parameter "aBlock", and defined by the block literal "[:aCharacter | aCharacter isVowel]"), answers a Boolean, which is then sent "ifTrue:". If the Boolean is the object true, the character is added to a string to be returned. Because the "select:" method is defined in the abstract class Collection, it can also be used like this:

| rectangles aPoint collisions |rectangles:=OrderedCollectionwith: (Rectangleleft:0right:10top:100bottom:200)   with: (Rectangleleft:10right:10top:110bottom:210).aPoint:=Pointx:20y:20.collisions:=rectanglesselect: [:aRect|aRectcontainsPoint:aPoint].

The exception handling mechanism uses blocks as handlers (similar to CLOS-style exception handling):

[   someoperation ] on:Errordo:[:ex|handler-codeexreturn ] 

The exception handler's "ex" argument provides access to the state of the suspended operation (stack frame, line-number, receiver and arguments etc.) and is also used to control how the computation is to proceed (by sending one of "ex proceed", "ex reject", "ex restart" or "ex return").

Classes

This is a stock class definition: [36]

Objectsubclass:#MessagePublisherinstanceVariableNames:''classVariableNames:''poolDictionaries:''category:'Smalltalk Examples'

Often, most of this definition will be filled in by the environment. Notice that this is a message to the Object class to create a subclass named MessagePublisher. In other words: classes are first-class objects in Smalltalk which can receive messages just like any other object and can be created dynamically at execution time.

Methods

When an object receives a message, a method matching the message name is invoked. The following code defines a method publish, and so defines what will happen when this object receives the 'publish' message.

publishTranscriptshow:'Hello World!'

The following method demonstrates receiving multiple arguments and returning a value:

quadMultiply:i1and:i2"This method multiplies the given numbers by each other and the result by 4."| mul |mul:=i1*i2.^mul*4

The method's name is #quadMultiply:and:. The return value is specified with the ^ operator.

Objects are responsible for determining dynamically at runtime which method to execute in response to a message—while in many languages this may be (sometimes, or even always) determined statically at compile time.

Instantiating classes

The following code:

MessagePublishernew

creates (and returns) a new instance of the MessagePublisher class. This is typically assigned to a variable:

publisher:=MessagePublishernew

However, it is also possible to send a message to a temporary, anonymous object:

MessagePublishernewpublish

Hello World example

The Hello world program is used by virtually all texts to new programming languages as the first program learned to show the most basic syntax and environment of the language. For Smalltalk, the program is extremely simple to write. The following code, the message "show:" is sent to the object "Transcript" with the String literal 'Hello, world!' as its argument. Invocation of the "show:" method causes the characters of its argument (the String literal 'Hello, world!') to be displayed in the transcript ("terminal") window.

Transcriptshow:'Hello, world!'.

To see the results of this example, a Transcript window must be open.

Image-based persistence

Most popular programming systems separate static program code (in the form of class definitions, functions or procedures) from dynamic, or run time, program state (such as objects or other forms of program data). They load program code when a program starts, and any prior program state must be recreated explicitly from configuration files or other data sources. Any settings the program (and programmer) does not explicitly save must be set up again for each restart. A traditional program also loses much useful document information each time a program saves a file, quits, and reloads. This loses details such as undo history or cursor position. Image based systems don't force losing all that just because a computer is turned off, or an OS updates.

Many Smalltalk systems, however, do not differentiate between program data (objects) and code (classes). In fact, classes are objects. Thus, most Smalltalk systems store the entire program state (including both Class and non-Class objects) in an image file. The image can then be loaded by the Smalltalk virtual machine to restore a Smalltalk-like system to a prior state. [37] This was inspired by FLEX, a language created by Alan Kay and described in his M.Sc. thesis. [38]

Smalltalk images are similar to (restartable) core dumps and can provide the same functionality as core dumps, such as delayed or remote debugging with full access to the program state at the time of error. [39]

Other languages that model application code as a form of data, such as Lisp, often use image-based persistence as well (see EMACS, for example). This method of persistence is powerful for rapid development because all the development information (e.g. parse trees of the program) is saved which facilitates debugging.

However, it also has serious drawbacks[ citation needed ] as a true persistence mechanism. For one thing, developers may often[ citation needed ] want to hide implementation details and not make them available in a run time environment. For reasons of legality and maintenance, allowing anyone to modify a program at run time inevitably[ citation needed ] introduces complexity and potential errors that would not be possible with a compiled system that exposes no source code in the run time environment. Also, while the persistence mechanism is easy to use, it lacks the true persistence abilities needed for most multi-user systems.[ citation needed ] The most obvious is the ability to do transactions with multiple users accessing the same database in parallel.[ citation needed ]

Level of access

Everything in Smalltalk-80, unless customised to avoid the possibility, is available for modification from within a running program. This means that, for example, the IDE can be changed in a running system without restarting it. In some implementations, the syntax of the language or the garbage collection implementation can also be changed on the fly. Even the statement true become: false is valid in Smalltalk, although executing it is not recommended except for demonstration purposes (see virtual machine, image-based persistence, and backups).

Just-in-time compilation

Smalltalk programs are usually[ citation needed ] compiled to bytecode, which is then interpreted by a virtual machine or dynamically translated into machine-native code.

List of implementations

OpenSmalltalk

OpenSmalltalk VM (OS VM) is a notable[ citation needed ] implementation of the Smalltalk virtual machine on which many modern Smalltalk implementations are based or derived from. [40] [41] OS VM itself is transpiled from a set of Smalltalk source code files (using a subset of Smalltalk named Slang) to native C language source code (by using a transpiler named VMMaker), [42] which is in turn compiled against specific platform and architecture of the hardware practically enabling cross-platform execution of the Smalltalk images. The source code is available on GitHub and distributed under MIT License. The known Smalltalk implementations based on the OS VM are: [43]

Others

JavaScript VM

See also

Related Research Articles

<span class="mw-page-title-main">Dylan (programming language)</span> Multi-paradigm programming language

Dylan is a multi-paradigm programming language that includes support for functional and object-oriented programming (OOP), and is dynamic and reflective while providing a programming model designed to support generating efficient machine code, including fine-grained control over dynamic and static behaviors. It was created in the early 1990s by a group led by Apple Computer.

<span class="mw-page-title-main">Ruby (programming language)</span> General-purpose programming language

Ruby is an interpreted, high-level, general-purpose programming language that supports multiple programming paradigms. It was designed with an emphasis on programming productivity and simplicity. In Ruby, everything is an object, including primitive data types. It was developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

<span class="mw-page-title-main">Self (programming language)</span> Prototype-based programming language

Self is an object-oriented programming language based on the concept of prototypes. Self began as a dialect of Smalltalk, being dynamically typed and using just-in-time compilation (JIT) as well as the prototype-based approach to objects: it was first used as an experimental test system for language design in the 1980s and 1990s. In 2006, Self was still being developed as part of the Klein project, which was a Self virtual machine written fully in Self. The latest version is 2017.1 released in May 2017.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

In computer programming, a generic function is a function defined for polymorphism.

Io is a pure object-oriented programming language inspired by Smalltalk, Self, Lua, Lisp, Act1, and NewtonScript. Io has a prototype-based object model similar to the ones in Self and NewtonScript, eliminating the distinction between instance and class. Like Smalltalk, everything is an object and it uses dynamic typing. Like Lisp, programs are just data trees. Io uses actors for concurrency.

In object-oriented programming, a metaclass is a class whose instances are also classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses. Among those that do, the extent to which metaclasses can override any given aspect of class behavior varies. Metaclasses can be implemented by having classes be first-class citizens, in which case a metaclass is simply an object that constructs classes. Each language has its own metaobject protocol, a set of rules that govern how objects, classes, and metaclasses interact. Metaclasses can be used, for example, to generate code automatically, or in developing frameworks.

In some programming languages, eval, short for the English evaluate, is a function which evaluates a string as though it were an expression in the language, and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval. The input to eval is not necessarily a string; it may be structured representation of code, such as an abstract syntax tree, or of special type such as code. The analog for a statement is exec, which executes a string as if it were a statement; in some languages, such as Python, both are present, while in other languages only one of either eval or exec is.

VisualWorks is a cross-platform implementation of the Smalltalk language. It is implemented as a development system based on images, which are dynamic collections of software objects, each contained in a system image.

<span class="mw-page-title-main">Class browser</span> Feature of coding platforms

A class browser is a feature of an integrated development environment (IDE) that allows the programmer to browse, navigate, or visualize the structure of object-oriented programming code.

Magik is an object-oriented programming language that supports multiple inheritance and polymorphism, and it is dynamically typed. It was designed and implemented in 1989 by Arthur Chance of Smallworld Systems Ltd. as part of Smallworld Geographical Information System (GIS). Following Smallworld's acquisition in 2000, Magik is now provided by GE Energy, still as part of its Smallworld technology platform.

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity which the currently running code is a part of. The entity referred to thus depends on the execution context. Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, these keywords can disambiguate variables and functions with the same name.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.

This comparison of programming languages compares how object-oriented programming languages such as C++, Java, Smalltalk, Object Pascal, Perl, Python, and others manipulate data structures.

<span class="mw-page-title-main">Pharo</span>

Pharo is an open source, cross-platform implementation of the classic Smalltalk-80 programming language and runtime. It is based on the OpenSmalltalk virtual machine called Cog (VM), which evaluates a dynamic, reflective, and object-oriented programming language with a syntax closely resembling Smalltalk-80.

<span class="mw-page-title-main">Object-oriented programming</span> Programming paradigm based on the concept of objects

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields, and code in the form of procedures. In OOP, computer programs are designed by making them out of objects that interact with one another.

<span class="mw-page-title-main">DrGeo</span>

GNU Dr. Geo is an interactive geometry software that allows its users to design & manipulate interactive geometric sketches, including dynamic models of Physics. It is free software, created by Hilaire Fernandes, it is part of the GNU project. It runs over a Morphic graphic system. Dr. Geo was initially developed in C++ with Scheme scripting, then in various versions of Smalltalk with Squeak, Etoys_(programming_language) for One Laptop per Child Pharo then Cuis-Smalltalk.

Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Due to Apple macOS’s direct lineage from NeXTSTEP, Objective-C was the standard programming language used, supported, and promoted by Apple for developing macOS and iOS applications until the introduction of the Swift programming language in 2014.

Citrine is a general-purpose programming language for various operating systems. It focuses on readability and maintainability. Readability is achieved by syntactic and conceptual minimalism. The language is heavily inspired by Smalltalk and Self but has some very distinctive features. Like Smalltalk, Citrine treats everything as an object and focuses on sending messages to these objects. However, unlike Smalltalk, Citrine lacks the concept of a class. In this regard, Citrine is more like Self and JavaScript because it uses prototypes. The combination of Smalltalk-like messages and prototypes is what makes Citrine unique.

References

  1. "Alto I Schematics" (PDF). Bitsavers. p. 54. Retrieved 21 July 2016.
  2. "History of Computers and Computing, Birth of the modern computer, Personal computer, Xerox Alto" . Retrieved 2016-04-19.
  3. 1 2 3 4 5 6 7 8 Kay, Alan; Ram, Stefan (2003-07-23). "E-Mail of 2003-07-23". Dr. Alan Kay on the Meaning of 'Object-Oriented Programming'. Retrieved 2009-01-03.
  4. 1 2 3 Kay, Alan. "The Early History of Smalltalk" . Retrieved 2007-09-13.
  5. "ANSI Smalltalk Standard". Smalltalk.org. 2004. Archived from the original on 2006-02-16. Retrieved 2021-03-02.
  6. "Stack Overflow Developer Survey 2017".
  7. "Stack Overflow Developer Survey 2018".
  8. "Versions". Smalltalk.org. Archived from the original on 2015-09-08. Retrieved 2007-09-13.
  9. "Tektronix invitation for First international Conference of Smalltalk-80 Implementors" (PDF). Tektronix Smalltalk Document Archive. 27 August 1981.
  10. "Attendee list for First international Conference of Smalltalk-80 Implementors" (PDF). Tektronix Smalltalk Document Archive. 24 September 1981.
  11. "Introducing the Smalltalk Zoo". CHM. 17 December 2020.
  12. "VI Release Notes" (PDF). 20 November 1981.
  13. 1 2 Ingalls, Daniel (2020). "The evolution of Smalltalk: from Smalltalk-72 through Squeak". Proceedings of the ACM on Programming Languages. 4: 1–101. doi: 10.1145/3386335 . S2CID   219603700.
  14. "ANSI Smalltalk Standard". Smalltalk.org. Archived from the original on 2015-09-07. Retrieved 2007-09-13.
  15. "Hobbes". Archived from the original on 19 April 2003.
  16. "History". Seagull Software. Archived from the original on 2002-08-06. Retrieved 2007-09-13.
  17. "VisualAge Smalltalk Transition FAQ".
  18. The Simula language was also object-oriented and preceded (and was acknowledged as an influence on) Smalltalk but it was a simulation language, not a general purpose programming language.
  19. Cannon, Howard. "Flavors A non-hierarchical approach to object-oriented programming" (PDF). softwarepreservation.org. Retrieved 17 December 2013.
  20. "About Ruby". ruby-lang.org. Retrieved 17 December 2013.
  21. "Where Did Refactoring Come From?". sourcemaking.com. Retrieved 17 December 2013.
  22. "DARPA – ARPA". livinginternet.com. Retrieved 16 December 2013. To meet this need, ARPA established the IPTO in 1962 with a mandate to build a survivable computer network to interconnect the DoD's main computers at the Pentagon, Cheyenne Mountain, and SAC HQ.
  23. "Engelbart's Role in Early Computer Networking". dougengelbart.org. Retrieved 17 December 2013.
  24. Krasner, Glen; Pope, Stephen (August–September 1988). "A Cookbook for Using the Model-View-Controller User Interface Paradigm in Smalltalk -80". Journal of Object-Oriented Programming.
  25. "Our Influence". cincomsmalltalk.com. Retrieved 16 December 2013.
  26. Kay, Alan (October 10, 1998). "Prototypes vs Classes (e-mail on Squeak list)".
  27. Goldberg, Adele; Robson, David (1989). Smalltalk-80 The Language. Addison Wesley. pp. 31, 75–89. ISBN   0-201-13688-0.
  28. Clark, A.N. (September 18, 1997). "Metaclasses and Reflection in Smalltalk". arXiv: 1804.07272 [cs.SE].
  29. Ducasse, Stéphane; Lienhard, Adrian; Renggli, Lukas. "Seaside – A Multiple Control Flow Web Application Framework" (PDF). scg.unibe.ch. Software Composition Group Institut fur Informatik und angewandte Mathematik Universitaat Bern, Switzerland. Retrieved 16 December 2013.
  30. Foote, Brian; Johnson, Ralph (1–6 October 1989). "Reflective facilities in Smalltalk-80". Conference proceedings on Object-oriented programming systems, languages and applications. pp. 327–335. doi: 10.1145/74877.74911 . ISBN   0-89791-333-7. S2CID   14207536 . Retrieved 16 December 2013.
  31. Smith, Brian C (1982-01-01). "Procedural Reflection in Programming Languages". MIT Technical Report (MIT-LCS-TR-272). Retrieved 16 December 2013.
  32. Peck, Mariano Martinez; Bouraqadi, Noury; Denker, Marcus; Ducasse, Stéphane; Fabresse, Luc (2011-08-23). Efficient proxies in Smalltalk. ACM. p. 1–16. doi:10.1145/2166929.2166937. hdl: 20.500.12210/28011 . ISBN   978-1-4503-1050-5.
  33. Ducasse, Stéphane (2001). "Squeak: Une syntaxe minimaliste / Squeak: A minimalist syntax!" (PDF). Programmez! Le Magazine du Développement. 1. Retrieved 15 January 2024.
  34. Ducasse, Stéphane. "Object-Oriented Design with Smalltalk — a Pure Object Language and its Environment" (PDF). Software Composition Group (University of Berne). Retrieved 15 January 2024.
  35. Goldberg, Adele; Robson, David (1989). Smalltalk-80 The Language. Addison Wesley. pp. 17–37. ISBN   0-201-13688-0.
  36. Goldberg, Adele; Robson, David (1989). Smalltalk-80 The Language. Addison Wesley. pp. 39–53. ISBN   0-201-13688-0.
  37. "Image-Based Persistence". book.seaside.st. Retrieved 17 December 2013.
  38. Kay, Allen (1968). "FLEX – A flexible extendable language". University of Utah MSC Thesis.
  39. Fowler, Martin. "Memory Image". martinfowler.com. Archived from the original on 2011-10-07. Retrieved 17 December 2013.
  40. "opensmalltalk-vm", OpenSmalltalk, Git hub, 2020-11-03, retrieved 2020-11-08
  41. Eliot Miranda; Clément Bera; Elisa Gonzalez Boix; Dan Ingalls (2018). Two Decades of Smalltalk VM Development: Live VM development through Simulation Tools; Virtual Machines and Language Implementations VMIL 2018, Boston, United States (Report). hal.archives-ouvertes.fr. doi:10.1145/3281287.3281295. Archived from the original on 2022-11-05.
  42. "Slang". Squeak. Retrieved 2020-11-08.
  43. 1 2 Miranda, Eliot; Bera, Clément; Gonzalez Boix, Elisa; Dan, Ingalls (October 8, 2018). "Two Decades of Smalltalk VM Development: Live VM development through Simulation Tool" (PDF).
  44. Table of Contents, Cuis Smalltalk, 2021-11-24, retrieved 2021-11-25
  45. Scott Warren (1979). A Language Lost to the Public – Rosetta Smalltalk Flap, 1979.
  46. "Strongtalk: A High-Performance Open Source Smalltalk With An Optional Type System" . Retrieved 2021-11-25.

Further reading