Smalltalk

Uses your system voice; voice and rate in settings.

Snapshot

≈ 25 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

Smalltalk is a purely object-oriented programming language 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. In Smalltalk, executing programs are built of opaque, atomic 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 numerous foundational ideas for the nascent field of object-oriented programming. Since inception, the language provided interactive programming using 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 is a purely object-oriented programming language 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. In Smalltalk, executing programs are built of opaque, atomic 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 numerous foundational ideas for the nascent field of object-oriented programming. Since inception, the language provided interactive programming using 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 communities of users around them. American National Standards Institute (ANSI) Smalltalk was ratified in 1998 and represents the standard version of Smalltalk. Smalltalk took second place for "most loved programming language" in the Stack Overflow Developer Survey in 2017, but it was not among the 26 most loved programming languages of the 2018 survey.

Influences

Smalltalk, itself based on Simula , influenced virtually all of the object-oriented languages that came after—Flavors, CLOS, Objective-C, Java, Python, Ruby, and many others. Smalltalk was frequently used for agile software development methods, rapid application development (RAD) or prototyping, and software design patterns. Smalltalk was often selected for rapid, iterative development due to the development speed the environment supported. Smalltalk emerged from a larger program of Advanced Research Projects Agency-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. Alan Kay (one of the inventors of Smalltalk) also described a tablet computer he named the Dynabook which resembles modern tablet computers. 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. In addition to the MVC pattern, the Smalltalk language and environment were 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. Smalltalk uses several collection filter operators that rhyme with the "-ect" suffix, collect:, select:, inject:into:, et al. This was inspired by a line from the 1967 Arlo Guthrie monologue "Alice's Restaurant Massacree," in which Guthrie underwent a battery of being "injected, inspected, detected, infected, neglected and selected."

Syntax

Smalltalk-80 syntax is rather minimalist, based on only a handful of declarations. In fact, there are only five "keywords" in Smalltalk, names of pseudo-variables with a special meaning: true , false , nil , self , and super . 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. The only built-in language constructs are message sends, assignment, method return, literal syntax for some objects, including block literals (closures). 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 pseudo-variable thisContext may have been added in some implementations, but is not mentioned in either Smalltalk-80 or the ANSI standard. Pseudo-variables in general realize arguments passed to messages or blocks; content of these variables is read-only and cannot be modified. 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 each 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: exampleWithNumber: x | y | true & false not & (nil isNil) ifFalse: [self halt]. y := self size + super size. #($a #a 'a' 1 1.0) do: [ :each | Transcript show: (each class name); show: ' ']. ^x

Literals

The following examples illustrate the most common objects which can be written as literal values in Smalltalk-80 methods. The following list illustrates some of the possibilities for numbers. 42 -42 123.45 1.2345e2 2r10010010 16rA000 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: #(1 2 3 4) defines an array of four integers. #((1 2 3 4) [1 2 3 4] 'four' 4.0 #four) defines a five element array whose first element is a literal array, second element a byte array, third element the string 'four', and so on. Many implementations support the following literal syntax for ByteArrays: #[1 2 3 4] defines a ByteArray of four integers. And last but not least, blocks (anonymous function literals) [... Some smalltalk code...] The following takes two arguments and compares any two objects which can understand "less than", for example numbers, and strings [:a :b| a 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, harkening 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). There are three kinds of message sends, unary messages, which have a single keyword, such as class and size , binary messages, which for example are used for arithmetic, such as a , a ~= b , and keyword messages where a keyword followed by a colon precedes each argument in the message, so that a between: b and: c sends the #between:and: message to a with arguments b and c . Unary messages have higher precedence than binary messages, which have higher precedence than keyword messages, and evaluation is strictly left-to-right. There is no arithmetic precedence. 1 + 2 * 3 evaluates to 9, not to 7. The following example sends the message 'factorial' to number 42: 42 factorial 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 := 42 factorial "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: 2 raisedTo: 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: $o startingAt: 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: new Rectangle(100, 200); It's unclear which argument is which. By contrast, in Smalltalk, this code would be written as: Rectangle width: 100 height: 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). The programmer is free to define new binary selectors just as they are free to define novel unary and keyword messages. 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

Smalltalk is an expression-based language. Every statement, including control constructs, has a value, which is some object. 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: 3 factorial + 4 factorial between: 10 and: 100 is evaluated as follows: 3 receives the message "factorial" and answers 6 4 receives the message "factorial" and answers 24 6 receives the message "+" with 24 as the argument and answers 30 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, (3 factorial + 4) factorial between: 10 and: 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: 3 factorial factorial log 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 (period is a statement separator, not a statement terminator). This example first creates a new instance of class Window, stores it in a variable, and then sends two messages to it. | window | window := Window new. window label: 'Hello'. window open 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: Window new label: '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 | ] Where :params is the list of parameters the code can take. This means that the Smalltalk code: [:x | x + 1] can be understood as: f(x) = x + 1 or expressed in lambda terms as: \lambda x.x + 1 and [:x | x + 1] value: 3 can be evaluated as f(3) = 3 + 1 Or in lambda terms as: (\lambda x. x + 1)\,3 \underset{\beta}\rightarrow 3+1 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 expr ifTrue: [statements to evaluate if expr] ifFalse: [statements to evaluate if not expr] True methods for evaluation False methods for evaluation positiveAmounts := allAmounts select: [:anAmount | anAmount isPositive] 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.

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 > b ifTrue:[ '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 := aString select: [:aCharacter | aCharacter isVowel]. 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 := OrderedCollection with: (Rectangle left: 0 right: 10 top: 100 bottom: 200) with: (Rectangle left: 10 right: 10 top: 110 bottom: 210). aPoint := Point x: 20 y: 20. collisions := rectangles select: [:aRect | aRect containsPoint: aPoint]. The exception handling mechanism uses blocks as handlers (similar to CLOS-style exception handling): [ some operation ] on:Error do:[:ex | handler-code ex return ] 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: Object subclass: #MessagePublisher instanceVariableNames: 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. publish Transcript show: 'Hello World!' The following method demonstrates receiving multiple arguments and returning a value: quadMultiply: i1 and: 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: MessagePublisher new creates (and returns) a new instance of the MessagePublisher class. This is typically assigned to a variable: publisher := MessagePublisher new However, it is also possible to send a message to a temporary, anonymous object: MessagePublisher new publish

Integrated Development Environment

Smalltalk is one of the first systems to be based around an Integrated Development Environment. There are a rich variety of tools to support code development, and other activities, such as graphics, and music. Smalltalk was the first system in which the modern desktop paradigm of Windows, Icons, Menus, and Pointers (WIMP) was created. Although pointers had already been invented, Smalltalk was the first system to implement overlapping windows and pop-up menus. While there are several programming tools we shall describe the following five major tools. The images of the tools are from a 2024 Squeak system browser, the main code viewing and writing tool workspace, a text editor in which expressions can be evaluate transcript, an output window for text, which in many dialects is also a workspace inspector notifier/debugger, a window opened in response to an unhandled exception, and can morph into a full debugger The Transcript is a special workspace associated with the global Transcript. So evaluating Transcript print: 52 factorial; cr; flush causes 80658175170943878571660636856403766975289505440883277824000000000000 followed by a newline to appear on the Transcript window. The Transcript therefore serves as a place to emit logging messages, although it can also function as a Workspace

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. Transcript show: '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. This was inspired by FLEX, a language created by Alan Kay and described in his M.Sc. thesis. 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. 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 as a true persistence mechanism. For one thing, developers may often 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 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. The most obvious is the ability to do transactions with multiple users accessing the same database in parallel.

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 compiled to bytecode, which is then interpreted by a virtual machine or dynamically translated into native machine-code. The results of previous message lookups are cached in self-modifying machine-code resulting in very high-performance sends that can out-perform the indirect function calls in C++ virtual method calls.

List of implementations

See also

Dart Objective-C Newspeak Ruby Self Strongtalk GLASS (software bundle) Distributed Data Management Architecture

Further reading

External links

A 1973 semantic description of Smalltalk written in itself Free Online Smalltalk Books

Text derived from https://en.wikipedia.org/w/index.php?oldid=1377717650 under CC BY-SA 4.0; modifications have been made.

Sources cited in this revision

34 named source(s) extracted from the cited revision. A source with no author is shown by its publication; nothing is invented.