If equality is only redefined 57 times, this definition must be good enough for the vast majority of classes.

The most important reason for implementing equality is because you are going to put your objects in a Collection and you want to be able to test for inclusion, remove elements, or eliminate duplicates in Sets without having to have the same instance.

For example, let's say I'm working on a library program. Two books are equal if the author and title are equal:

```perl
Book>>= aBook
^self author = aBook author & (self title = aBook title)
```

A Library maintains an OrderedCollection of Books. Because I have defined equality, I can write a method that takes the name of an author and a title and searches for that Book:

```perl
Library>>hasAuthor: authorString title: titleString
I book I
book := Book
author: authorString
title: titleString.
^self books includes: book
```

The other major reason to implement equality is because your objects have to interoperate with other objects that implement equality. For example, if I was implementing a new kind of Number, I would define equality because all Numbers define equality.

You see a fair number of class tests in equality methods. For example, you might see:
```
Book>>= aBook
(aBook isMemberOf: self class) ifFalse: [^false].
^self author = aBook author & (self title = aBook title)
```

I read this as "If aBook isn't a Book, I couldn't possibly be equal to it. Otherwise, I'm equal if my author and title are equal to aBook's." While class tests are in general a bad thing (see Choosing Message), this is one place where they can be useful. What if we want to add Videos to our Library? Videos don't have a message "author," so comparing a Book and a Video without some protection would result in an error.

* If you will be putting objects in a Set, using them as Dictionary keys, or otherwise using them with other objects that define equality, define a method called "==." Protect the implementation of "==" so only objects of compatible classes will be fully tested for equality.

Value-like objects, like Numbers and Points, are the most obvious candidates for Equality Methods. Two Points are equal if their coordinates are equal.

```
Point>>= aPoint
(aPoint isMemberOf: self class) ifFalse: [^false].
^x = aPoint x & (y = aPoint y)
```

BACK

You may need Double Dispatch (p. 55) for complex multiclass equality tests. Testing is often done in terms of Simple Delegation (p. 65) with one or more components of an object.

BACK

## Hashing Method

You have written an Equality Method (p. 124). You may be putting new objects into a Set (p. 119). You may be using a new object as a key in a Dictionary (p. 128).
* How do you ensure that new objects work correctly with hashed Collections?

Once you understand the idea that you can override “=,” the world becomes your oyster. New objects that have their own definition of equality automatically begin to play nicely with the rest of Smalltalk—almost.

Collection>>includes: uses equality:

Collection>>includes: anObject
self do: [:each | each = anObject ifTrue: [^true]].
^false

So, you start out with an OrderedCollection and your newly equal objects and everything works fine. Then, you decide you need a Set. All of a sudden, you start getting bugs. You look at a Set and it has two objects in it that you know are equal. Weren't Sets supposed to avoid that problem?

The problem is that Set>>includes: doesn't just send “=,” it also sends “hash.” If two objects are equal but they don't return the same hash value, the Set is likely to miss the fact that they are equal.

* If you override “=” and use the object with a hashed Collection, override “hash” so that two objects that are equal return the same hash value.

This rule may seem kind of abstract. In practice, though, it is simple to satisfy this constraint. The Equality Method typically relies on some set of messages returning results that are equal:

Book>>= aBook
^self title = aBook title & (self author = aBook author)

My first cut implementation of “hash” is to get the hash values of all the messages that the Equality Method relies on and put them together with bit-wise exclusive-or.
### Book>>hash

^self title hash bitXor: self author hash

This works whether the messages return Strings, Numbers, Arrays, or whatnot, because all the sub-components obey the Hashing Method pattern.

Hashing is often implemented in terms of Simple Delegation (p. 65).

BACK

## Dictionary

BACK

You need a Collection (p. 115) that is indexed by something other than consecutive integers.

* How do you map one kind of object to another?

Arrays and OrderedCollections map integers into objects. The integers must be between one and the size of the collection. Dictionaries are more flexible maps. Their keys may be any objects, instead of having to be sequential integers.

A typical use of a Dictionary is to map the names of things to the things:

### colors

I result I

result := Dictionary new.

result

at: 'red'

put: (Color red: 1).

result

at: 'gray'

put: (Color brightness: 0.5).

^result
Another way to solve this problem is to add a "name" instance variable to Color. In fact, this seems to me the more "object-oriented" solution. Why doesn't this work?

Different parts of the system will want different names for the same color. A color called "red" in one place will be called "warning" in another. I suppose you could add a "colorName" and a "purposeName" instance variable to Color. Where would this end? Every new application of color would have to add a new instance variable. It is much easier to use a Dictionary in each object that needs a unique name.

Another way to solve this problem is to create an object that wraps a Color and gives it a name.

NamedColor
superclass: Object
instance variables: name color

Whenever I have implemented an object like this, it never gains any more
responsibility than Getting Methods for the name and the wrapped object. It
isn't worth it to create a new object just to do that. Associating a name with a
color using a Dictionary only takes a few lines and is easily understood.

* Use a *Dictionary*.

A common use for Dictionaries is giving names to things. For example, if I have a widget and different colors have different meanings, I might store them in a Dictionary:

Widget>>defaultColors
I results I
results := Dictionary new.
results
    at: 'foreground'
    put: Color black.
results
    at: 'background'
    put: Color mauve.
^results
Sometimes, programmers in a hurry use Dictionaries as cheap data structures. You can always spot code like this because two or more methods will use exactly the same fixed set of keys.

```csharp
vitalInformation
    l result l
    result := Dictionary new.
    result
        at: 'weight'
        put: 190.
    result
        at: 'hair'
        put: 'blond'.
    ^result
checkOut: aPerson
    l info l
    info := aPerson vitalInformation.
    (info at: 'weight') < 280 & ((info at: 'hair') = 'black')
ifTrue: ...
```

I've also done the same thing with Arrays of fixed size where different indexes mean different things:

```csharp
vitalInformation
    ^Array
        with: 190
        with: 'blond'
checkOut: aPerson
    l info l
    info := aPerson vitalInformation.
    (info at: 1) < 280 & ((info at: 2) = 'black') ifTrue: ...
```
This is your program's way of telling you "There's a new object here." The new object will have one instance variable for each element in the collection.

*If you implement an Equality Method (p. 124) for Dictionary keys, you must also implement a Hashing Method (p. 126).*

BACK

SortedCollection

BACK

*You have a Collection (p. 115) that needs to be ordered according to some attributes of the elements.*

* How do you sort a collection?

When I was in college, sorting was a big deal. I studied Knuth. I learned a dozen clever ways to sort. I listened to all the stories about how much computing time went into sorting algorithms and what an amazing impact even small improvements could have.

Imagine my distress when, after eleven years of Smalltalk programming, I have yet to write a sorting algorithm. All those brain cells wasted!

Not wasted, of course. To be an accomplished programmer you have to know what's going on under the hood. It's just that Smalltalk's collection classes turn awareness of how sorting is implemented into a rare and spectacular event.

Just as you have collections whose order is determined by when elements were added (OrderedCollection) and unordered but efficient (Set), sorting is just another attribute of a special kind of collection, SortedCollection.

* Use a SortedCollection. Set its sort block if you want to sort by some criteria other than "<=".

Any collection can be sorted by sending it "asSortedCollection."

By default, SortedCollections use "<" to compare elements. Numbers, Strings, Date and Time, and a few other objects already define "<." You will have to define "<" for your objects if you intend to put them in the result of "SortedCollection new."
SortedCollections internally use a two argument block to compare
elements. You can set this sort block to anything you want. I could
sort my children by age:

childrenByAge
^self children asSortedCollection: [:a :b | a age < b age]

because ages are Numbers and numbers define "<." I could just as
easily sort them alphabetically by name:

children byName
^self children asSortedCollection: [:a :b | a name < b
name]

If you already have a SortedCollection and you want to change its
order, you can send it "sortBlock: aBlock" to change the order.

self childrenByAge sortBlock: [:a :b | a income > b income]

One performance nasty to look out for is if you build a
SortedCollection one element at a time. SortedCollections re-sort
every time an element is added or deleted. If you need to build a
SortedCollection an element at a time, consider using an
OrderedCollection temporarily, then turning it into a
SortedCollection when it is complete.
<figure><img src="image_12.png" /></figure>

# Array

> You need a Collection (p. 115) with a fixed number of elements. You may have been using an OrderedCollection (p. 116).

* How do you code a collection with a fixed number of elements?

OrderedCollection extols the virtues of flexibility. How many elements do you need? Why decide now? Just use an OrderedCollection and avoid any arbitrary limits.

What if you know when you create it exactly how big a collection will be? You could use an OrderedCollection and add elements, but the code would have lost the information that the size of the collection is fixed. Your code will communicate better if you say, “Here’s a collection. Here’s how big it is. That won’t ever change.”

The second reason to use a fixed size collection is efficiency. The flexibility of an OrderedCollection comes at the cost of an extra message to access elements. Most implementations also split OrderedCollections into two objects, so there is extra space overhead as well.

Usually, you don’t care about the efficiency, but I did one performance tuning gig where I got a 40 percent speed-up by replacing the OrderedCollections with Arrays. Of course, the code looked like FORTRAN, not Smalltalk, but when you’re tuning performance you’re not out to save the world, just make it go a little faster.

* Use an Array. Create it with "new: anInteger" so that it has space for the number of elements you know it needs.

Ward Cunningham taught me the trick of simulating variable sized arrays. It is only valid if you are accessing the Array much more than you are adding to it and removing from it. Code that reads:

```
children := OrderedCollection new
```
you change into:

```
children := Array new "or even #()"
```

When you need to add an element, instead of adding it to the collection:

```
children add: anObject
```

you create a new Array with the element added and assign it to the variable:

```
children := children copyWith: anObject
```

Similarly, for removing elements:

```
children remove: anObject
```

you create a new Array without the element:

```
children := children copyWithout: anObject
```
<figure><img src="image_13.png" /></figure>

Use a **ByteArray** (p. 135) to store SmallIntegers in the range 0..255. Use an **Interval** (p. 137) to represent an Array of sequential Numbers. Use a **RunArray** (p. 118) to compactly store Arrays that have long runs of repeated elements.

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

## ByteArray

You need to represent an Array (p. 133) of small numbers.

* How do you code an Array of numbers in the range 0..255 or -128..127?

Software engineering was born in a resource starved environment. There have never been enough cycles or enough memory to do what we want. While this was more true in the past than it is today, the increasing demands of application consumers will always push the available resources.

One of the most creative reactions to the lack of available memory has been the ways software engineering has found to use eight bit bytes. The EBCDIC and ASCII codes encode printable characters as bytes. The P-Code and Smalltalk byte code instruction sets encode virtual machine instructions as bytes. The concatenation of four or eight bytes can form a memory address.

On the one hand, you would like your Smalltalk program to be as insulated as possible from representation decisions, in order to be as flexible as possible. On the other hand, some consideration of space efficiency must be possible so you can code in a still finite environment.

There are times when you really mean to communicate that information is stored as eight bit bytes. Then, using a more general representation would actually be misleading. You want to use the representation that most directly communicates your intent.

The collection classes provide an excellent means for achieving the flexibility of a hidden representation and the space efficiency of encoding information as bytes. Choosing a representation that stores only bytes effectively communicates that the objects contained in that collection can only be SmallIntegers in the range 0..255.

* Use a **ByteArray**.

ByteArrays are used to store homogenous information, like the pixels in an image or the floating point numbers in a vector.
Class: Vector
superclass: Object
instance variables: numbers

When you create a Vector of a certain size, it allocates enough bytes to store that many Floats:

Vector class>>new: anInteger
^self new setNumbers: (ByteArray new: anInteger * 4)
Vector>>setNumbers: aByteArray
numbers := aByteArray

Setting an element in a Vector takes the bytes out of the Float and puts them into the ByteArray:

Vector>>at: anInteger put: aFloat
1 to: 4 do:
    [each |
    numbers
        at: anInteger * 4 + each + 1
        put: (aFloat basicAt: each)]

When SmallIntegers are in a ByteArray, they are represented much as you would represent them in C or assembly language—simple eight bit patterns. The code for `at:put:` converts from Smalltalk's format for SmallIntegers into eight bit patterns. The code for `at:` does the reverse conversion.

If you are storing lots of information as bytes, you may find dramatic increases in speed or decreases in memory footprint after changing a few references to "Array" into references to "ByteArray." For
current Smalltalk systems with 32-bit object references, the savings is a factor of four. If you have lots of small ByteArrays, don't expect the same savings because the space overhead of each BeanArray (typically 8 or 12 bytes) will be large compared to the information stored in it.

Interval

* How do you code a collection of numbers in sequence?

Every once in a while, you will find yourself writing code to create an Array and initialize its elements to sequential numbers:

```perl
l indexes l
indexes := Array new: 100.
1 to: indexes size do:
    [:each l
    indexes
        at: each
        put: each]
```

This is not a very direct way to communicate “an Array of sequential numbers.” Also, it takes space and time to represent an Array of numbers like this.

There is a special collection class called Interval that is built expressly for this purpose. There is really no down side to using Interval. Your code will read better and be faster.

* Use an *Interval* with start, stop, and an optional step value. The *Shortcut Constructor Methods Number>>to*: and to:by: build *Intervals* for you.

Some of the code you write using Intervals can be confusing at first.

1 to: 20 do: [:each | ...]
is equivalent to:

(1 to: 20) do: [:each | ...]

Even though the two phrases look similar, very different code is being invoked. In the first case, the message `to:do:` is being sent to the `SmallInteger 1`. In the second, the message `to:` is being sent to the `SmallInteger 1`. This returns an `Interval` that is then sent the message `do:`.

You can translate prose descriptions of number sequences into `Intervals`:

<table><thead><tr><td>Description</td><td>Interval</td></tr></thead><tbody><tr><td>One to ten</td><td>1 to: 10</td></tr><tr><td>Even numbers from zero to fifty</td><td>0 to: 50 by: 2</td></tr><tr><td>Count down from 99 ? by threes</td><td>99 to: 0 by: -3</td></tr></tbody></table>

There are some enumerations you'd like to do that aren't supported by the enumeration protocol. For example, although there is a `Number>>to:do:`, there isn't a `Number>>to:collect:`. However, you can use an `Interval` because it is a full fledged collection.

For example, if I have an `Array` and I want an `Array` of `Associations`, the keys of which are the indexes of the original `Array` and the values of which are the elements, I can write:

(1 to: anArray size) collect:
    [:each |
        Association
            key: each
            value: (anArray at: each)]
## Collection Protocol

The uniform protocol of the collection classes are one of their greatest strengths. Client code is effectively decoupled from decisions about how to store a collection by using a common set of messages.

Many Smalltalk programmers take a long time to learn all the collection protocol. They begin with a couple of messages, like do:, add:, and size, and then stick with them for a long time.

When I started programming in Smalltalk, I can remember being overwhelmed by it. There is a lot to learn just to achieve basic competence. However, the collection protocol is one of the highest leverage pieces of the system. The better you can use it, the faster you can code and the faster you can read other folks' code.

This section highlights the most important messages in the collection repertoire. It is by no means exhaustive. I selected these messages to pattern because they are the ones I see most often missed or misused.

After you master these messages, take a day or so to make a thorough study of which messages are available in which collection classes. In no time, you'll be coding collections like a pro.

## IsEmpty

* How do you test if a collection is empty?

I wouldn't have thought I'd have to point this one out, but over and over I see code that says:

...aCollection size = 0 ifTrue: ...

or
...aCollection size > 0 ifTrue: ...

Checking whether size is equal to zero or greater than zero is really an
implementation of a higher level concept, namely "Is the collection empty?"

The collection protocol provides simple messages that test collections for emptiness. Using them results in more readable code.

* Send `empty` to test whether a collection is empty (has no elements). Use `notEmpty` to test whether a collection has elements.

All the Smalltalks have a simple facility for popping up a dialog that
asks the user to type in an answer. A blank answer indicates that the
operation shouldn't proceed. The following code (VisualWorks
style) is common:

I answer I
answer := Dialog request: 'Number, please?'.
answer empty ifTrue: [^self].
...

Note that while VisualSmalltalk and VisualAge also define
notEmpty, VisualWorks 2 does not, so you'll have to add it yourself.

The value of `empty` is not that there is such a huge difference
between:

`aCollection size = 0`

and:
aCollection empty

although there is some difference. The important point is that I can
read the idiomatic version instantly. If I see some code explicitly
checking the size, I have to stop and figure out if there is something
special going on that isn't obvious.

All cultures develop their own vocabulary. If you were in a repair
shop and you heard someone say, "hand me that wrench with the
knurled wheel that changes the width," you wouldn't want them
working on your car. You want a mechanic who knows it's a mon-
key wrench.

Includes:

* How do you search for a particular element in a collection?

Many people's first instinct is to use the enumeration protocol to imple-
ment searching. They will write code like this:

I found I
found := false.
aCollection do: [:each I each = anObject ifTrue: [found :=
true]].
...

With more experience, you might see a more sophisticated enumeration
message:
I found I
found := (aCollection
detect: [:each I each = anObject]
ifNone: [nil]) notNil.
...

The collection protocol provides you with a message to do exactly this, includes:.

The above code would look like this using includes:

I found I
found := aCollection includes: anObject
...

You could probably even eliminate the temporary variable and just use the expression in line.

Importantly, includes: is available to be optimized. Some kinds of collections, like Set, execute it in constant time, independent of the size of the collection. The alternatives to includes:, above, will always take time proportional to the size of the collection.

* *Send includes: and pass the object to be searched for.*

An example from Collection Accessor Method returns true if the receiver employs a person:

employs: aPerson
^employees includes aPerson
A common use of `includes` is to compute the intersection of two collections:

```javascript
collection1 select: [:each | collection2 includes: each]
```

BACK

*You will have to implement an Equality Method (p. 124) and a Hashing Method (p. 126) for your own objects, if you want to search based on contents instead of identity.*

## Concatentation

* How do you put two collections together?

Concatentation is one of those intermediate idioms in most languages. You can get along without it but pretty soon you have to learn how. The typical concatenation idiom goes something like this:

1. Create a collection big enough for the result.

2. Copy the first collection into the first part of the result.

3. Copy the second collection into the second part of the result.

Sometimes, there is a library function to do both copies for you.

Smalltalk simplifies this to a single message you send to the first collection, “,” (comma), with the second collection as an argument.

Many programming languages treat strings specially. Often, the “+” (plus) operator is used for string concatenation. In Smalltalk, Strings are just collections of characters. All the usual collection protocol works. In particular, to concatenate strings, you use “;” just as you would if you were dealing with Arrays or OrderedCollections.

*Concatenate two collections by sending “,” to the first with the second as an argument.*

Concatentation is often used when constructing messages from a String and some arguments:
self error: anInteger printString, ' is too many objects for ', aString

FORWARD

*You may need a Concatenating Stream (p. 165) if you are putting together lots of collections.*

Enumeration

* How do you execute code across a collection?

Once you have a collection, you have to do something with it. Examples
of computations across collections are:

* An Account computes its balance by totaling up the values of all of its Transactions.

* A composite Visual displays by displaying all of its components.

* Deleting a Directory deletes all of its Files.

Procedural programmers develop a toolbox of idioms for writing code like this. Ask a C programmer to iterate over an array, and chances are they will be able to program as fast as they can type. Visual recognition of such code becomes automatic, also.

Smalltalk hides the details of iteration behind a set of uniform messages that all collections understand. Rather than have one, two, or three line idioms, Smalltalk uses single word messages. Code written using these messages is easy to write correctly and easy to read correctly.

Because there are several variations on the enumeration messages, some Smalltalk programmers learn one or two and code the rest by hand. In the end, it takes longer to write code that is bigger, more error prone, and harder to read than if they just used the messages that are there.

* Use the enumeration messages to spread a computation across a collection.

Enumeration messages work fine for empty collections. You can use
this to avoid special case code for the case that a collection is
empty.
```groovy
printChildren
  children empty ifTrue: [^self].
  self children do: [:each | each print]
```

is exactly the same as:

```groovy
printChildren
  self children do: [:each | each print]
```

You will have problems if you are iterating over a Collection at the same time you are adding or removing elements:

```groovy
aSet do: [:each | aSet remove: each]
```

There isn't often a call to write this kind of code. If you must, make a copy of the collection to enumerate:

```groovy
aSet copy do: [:each | aSet remove each]
```
## Do

* How do you execute code for each element in a collection?

This is the fundamental message out of which the rest of the enumeration messages are built. If this were a procedural language, you would have a small set of idioms for iterating through a collection, one for a linked list, one for an array, one for a hash table.

For purposes of enumeration, there is no difference between the collection classes in Smalltalk. As a programmer, you never explicitly deal with walking pointers along a list or iterating a loop counter. You just send the message “do:” and magic happens.

In spite of the simplicity of `do:`, I still occasionally see code where someone slips into previous habits and writes:

```perl
index := 1.
[index <= aCollection size] whileTrue:
    [...aCollection at: index...
    index := index + 1]
```

There is really no excuse for this. The code using `do:` is much shorter and easier to read:

```perl
aCollection do: [:each I ...each...]
```

There is a small performance difference between the two. I measured open coded iteration on VisualSmalltalk for Windows 3.0.1 at 1 millisecond for a thousand element Array, while sending `do:` took 1.7 milliseconds. If you are doing any processing at all on the elements, the loop overhead will immediately disappear, and if you have to go in later and open code a few iterations, it is no big deal.
* Send do: to a collection to iterate over its elements. Send a one argument block as the argument to do: It will be evaluated once for each element.

Operations like `Collection>>add:` that are also defined for a Collection of parameters (`Collection>>addAll:`) are often implemented with `do:` and the simpler operation:

```pascal
Collection>>allAddAll: aCollection
aCollection do: [:each I self add: each]
```

I was raised on Pascal and C. I got good at writing loops, putting the index increments in just the right place. After about six months of Smalltalk, though, I just couldn't seem to remember to manually update loop indexes when I had to write out an enumeration by hand. I would always forget to put the increment in, or I'd decrement instead of increment. It was embarrassing at times. I'm happy to say, I've mostly recovered since then, but it's kind of a nice skill to be able to lose.

**Use a Simple Enumeration Parameter (p. 182) in the block.**

FORWARD

## Collect

* How do you operate on the result of a message sent to each object in the collection?

If this was good old procedural programming, we'd probably write code where the enumeration block sent a message to the element, then used the result of the message in further computation.

```pascal
self children do: [:each I self passJudgement: each hairStyle]
```
Other code, that also wanted to deal with hair styles, would have similar code:

```javascript
self children do: [:each | self trim: each hairStyle]
```

This violates the once and only once rule. The two code fragments look very similar except for the operation to be performed on the hair style.

We can capture the commonality of the code by creating an intermediate collection that contains the results of the messages sent to each element of the original collection. We can then enumerate over the new collection.

The new clarity of the code comes at the cost of creating a new collection to hold the transformed elements and iterating over the collection twice: once to transform it and once to compute with it. If you measure a performance problem coming from intermediate collections, it is easily fixed later. Better communication is definitely worth the cost, and chances are you'll never have a performance problem because of it.

* Use `collect:` to create a new collection whose elements are the results of evaluating the block passed to `collect:` with each element of the original collection. Use the new collection.

We can use Composed Method with `collect:` to capture the common part of the above code:

```javascript
childrenHairStyles
  ^self children collect: [:each | each hairStyle]
```

Then we can simplify the code fragments:

```javascript
self childrenHairStyles do: [:each | self passJudgement: each]
self childrenHairStyles do: [:each | self trim: each]
```
<figure><img src="image_15.png" /></figure>

> If you must, improve performance of code using collect: with a special Enumeration Method (p. 144). Use a Simple Enumeration Parameter (p. 182) in the block argument.

## Select/Reject

* How do you filter out part of a collection?

The procedural solution is to have an enumeration block that does two things—test the element for “interesting-ness” and conditionally perform some action on the interesting ones. Code written in this style looks like this:

```javascript
self children do: [:each | each isResponsible ifTrue: [self
buyCar: each]]
```

Code like this is fine the first time you write it, but chances are more
than likely that you'll want the same filter somewhere else:

```javascript
self children do: [:each | each isResponsible ifTrue: [self
addToWill: each]]
```

Remember the rule about saying things once and only once? These two
pieces of code violate that rule. Everything up to that second square bracket is
exactly the same. We'd like to capture that commonality, somehow.

The solution is to create a collection containing only interesting elements,
then operating on that. The new collection comes at a cost—it has to be creat-
ed separately from the original collection. What is an efficient garbage collec-
tor for, if not to let you make your code more expressive. If creating the inter-
mediate collections is too expensive, you can easily fix them later.

* Use `select:` and `reject:` to return new collections containing only elements of interest. Enumerate the new collection. Both take a one argument Block that returns a Boolean. `Select:` gives you ele-
ments for which the Block returns true, reject: gives you elements for which the Block returns false.

To capture the commonality of the above two pieces of code, we use Composed Method with select: to create a method that returns responsible children:

responsibleChildren

^self children select: [:each | each isResponsible]

Then we can simplify the two code fragments:

self responsibleChildren do: [:each | self buyCar: each]

self responsibleChildren do: [:each | self addToWill: each]

FORWARD

You can use a special purpose Enumeration Method to avoid the cost of creation. Use a Simple Enumeration Parameter in the block argument. Use a Lookup Cache to optimize performance.

## Detect

* How do you search a collection?

Another common collection idiom is searching for an element that meets certain criteria. Of course, you can implement this using `do:`, testing the criteria inside the enumeration block, and executing some code conditionally. This code gives the car keys to the first responsible child:
```javascript
self children do: [:each | each isResponsible ifTrue: [each
giveKeys: self carKeys. ^self]]
```

Notice that you have to be sure to only execute the conditional code once. Managing this in a complex loop can result in code that is very hard to follow.

* Search a collection by sending it `detect:`. The first element for which the block argument evaluates to true will be returned.

`Detect` takes a one argument block as an argument, which should evaluate to true or false. It returns the first element for which the block evaluates to true. The code above turns into:

```javascript
(self children detect: [:each | each isResponsible])
giveKeys: self carKeys
```

There is a variation of `detect:`, `detect:ifNone:`, that takes an additional zero parameter Block as an argument. Use this if you're not sure any element will be found.

`Detect:ifNone:` gives rise to a clever ("hard to read, at least at first") idiom. What if you want to return true from a method if any element meets a criterion and false otherwise?

```javascript
hasResponsibleChild
self children
detect: [:each | each isResponsible]
ifNone: [^false].
^true
```

I use this occasionally but I can't say I'm particularly proud of it.
Use a Simple Enumeration Parameter (p. 182) in the first block argument. Use a Lookup Cache (p. 161) to optimize performance.

## Inject:into:

You need an Enumeration (p. 144) that keeps a running value.

* How do you keep a running value as you iterate over a Collection?

One of the first procedural programming patterns everyone learns is keeping a running total.

1. Initialize the total.

2. For each element of a collection, modify the total (sum, min, max, whatever).

3. Use the result.

Thus, you see a lot of Smalltalk code that looks like this:

```perl
I max I
max := 0.
self children do: [:each I max := max max: each value].
^max
```

This is so common, in fact, that there is a message that does it for you.

Why doesn't everybody use this mysterious and powerful message? Because it has a funky name. People see the name and they think, "No way can I figure out what that does. Better leave it alone." This is no excuse for not using it, though. When what you mean is "Keep a running value over this collection," you should use the message, strange name and all.

* Use `inject:into:` to keep a running value. Make the first argument the initial value. Make the second argument a two element block. Call the block arguments `sum` and `each`. Have the block evaluate to the next value of the running value.
The code above becomes:

```clojure
^self children
  inject: 0
  into: [:sum :each I sum max: each]
```

There is a clever use of `inject:into`: that I just learned. Usually, I use "clever" as an insult but I just can't help but show this one. The problem is iterating over adjacent pairs in a collection. That is, I want to evaluate some code for elements one and two, then elements two and three, and so on. Here's how you use `inject:into`: for this:

```clojure
self children
  inject: nil
  into:
    [:eachPrevious :eachNext I
     eachPrevious notNil ifTrue: [...].
     eachNext]
```

The first time through the loop, `eachPrevious` is `nil` and `eachNext` is the first element of the collection. The conditional code isn't evaluated. The whole block evaluates to the first element of the collection. The second time through, `eachPrevious` is the first element of the collection and `eachNext` is the second element. The conditional code gets executed. This keeps going until `eachPrevious` is the second to last element and `eachNext` is the last element.

## Collection Idioms

Once you are comfortable using the collection protocol, you can begin using collections to solve higher level tasks. Here are a few of the common ways collections are used.
<figure><img src="image_16.png" /></figure>

# Duplicate Removing Set

You have a Collection (p. 115).

* How do you remove the duplicates from a Collection?

I remember answering this question on a test in school. I know I've seen the C-ish code for it while reviewing code. It always looks ugly:

```pascal
unique := OrderedCollection new.
self owners do: [:each | (unique includes: each) ifFalse:
[unique add: each]]
```

No need for that in Smalltalk. Once you get over the idea that allocating memory is expensive in programming or execution time, and once you get used to the power of the Collection classes, problems like this become trivial.

* Send "asSet" to the Collection. The result will have all duplicates removed.

If I want a Collection containing all my children with blue eyes or blond hair, where some children may have both, I can use this pattern.

```pascal
I nordic |
nordic := (self blueEyedChildren, self
blondHairedChildren) asSet.
...
```

I sure wish I'd been using Smalltalk when I was in college!

When you tune performance, you may find that you are creating Collections for the same elements over and over and over. Composing all those intermediate Collections together is no big deal. Remember, you're going for clarity of expression.
FORWARD

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

BACK

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

*Use a Temporarily Sorted Collection (p. 155) if you need the unique elements sorted.*

## Temporarily Sorted Collection

*You have a Collection (p. 115). You may have implemented a Comparing Method (p. 32) but want to sort the objects differently.*

* How do you present a Collection with one of many sort orders?

The obvious solution is to store the Collection as a SortedCollection in the first place. Every time you change the sort order, you can change the sort block of the SortedCollection.

If you wouldn't otherwise have to have the Collection sorted, this solution causes more problems than it solves. You may not want to pay the price of a SortedCollection most of the time. You may want several sort orders at the same time.

You can solve the problem by handing out copies of the Collection. Then you have the problem of coordinating additions and removals from the Collection. This problem is usually much less severe than trying to manage several sort orders with the same Collection.

* Return a sorted copy of the Collection by sending "asSortedCollection" to the Collection. Send "asSortedCollection: aBlock" for custom sort orders.

A common use for this pattern is presenting information in a list, especially if you have just used Duplicate Removing Set:

```
candidateList
    ^self candidates asSet asSortedCollection: [:a :b | a
    name < b name]
```
# Stack

* How do you implement a stack?

One of the first objects many people write when they come to Smalltalk is Stack. Stack is the basic data structure, fabled in song, story, and hundreds of papers about theoretical programming languages.

Algorithms that use stacks can be simply expressed in Smalltalk. The syntax lends itself to readable code written in terms of pushes and pops. However, there is no Stack class in any of the basic images. I've seen one written any number of times, but they never seem to last long. Smalltalk programmers need stacks, too. What do they do?

It's easy to simulate a stack using OrderedCollection:

<table><thead><tr><td>Stack Operation</td><td>OrderedCollection message</td></tr></thead><tbody><tr><td>push</td><td>addLast:</td></tr><tr><td>pop</td><td>removeLast:</td></tr><tr><td>top</td><td>last</td></tr><tr><td>depth</td><td>size</td></tr><tr><td>empty</td><td>empty</td></tr></tbody></table>

The result doesn't read exactly like a stack would read, but the idiom is so recognizable that the cost of using the idiom is far less than the cost of adding a new class to the image.

Why doesn't this result in confusing code? Why don't you write part of the algorithm using an OrderedCollection as a stack, then forget and start using it as a queue?

If there is a part of the algorithm that is complicated, you make a method or an object that gives it a simple public face. When you ask of the result "How many methods know this OrderedCollection is really a stack?," the answer is typically one. You use a Role Suggesting Temporary Variable name to communicate that the OrderedCollection is being used as a stack. End of story.

Why is there no Stack in Smalltalk? Well, "just because." It is part of the culture to simulate stacks using OrderedCollection. If that's how everybody does it, and it doesn't cost you anything, that's how you do it, too.

* Implement a Stack using an OrderedCollection.

If your stack only needs to be used within a single method, you can store it in a temporary variable:
```java
I tasks newTask nextTask |
...
...tasks addLast: newTask...
...
...nextTask := tasks removeLast...
...
```

If the whole object needs to share the stack, communicate the presence of the stack with Intention Revealing Messages:

```java
pushTask: aTask
    tasks addLast: aTask
popTask
    ^tasks removeLast
```

BACK

> You may need Composed Method (p. 21) to simplify code using OrderedCollections (p. 116) as Stacks, so the idiom is not confusing.

## Queue

* How do you implement a queue?

The story for queues is much like the story for stacks. Everyone simulates them using OrderedCollections:

<table><thead><tr><td>Queue Operation</td><td>OrderedCollection message</td></tr></thead><tbody><tr><td>add</td><td>addFirst:</td></tr><tr><td>remove</td><td>removeLast:</td></tr><tr><td>empty</td><td></td></tr><tr><td>length</td><td>size</td></tr></tbody></table>
As with stacks, you lose a little by translating the queue operations into
messages to OrderedCollection protocol, but not nearly enough to make up for
the cost of adding a new class.

* Implement queues using an OrderedCollection.

I have used OrderedCollections as queues a couple of ways. The
most common is in implementing level-order traversal, where you
need to visit all the depth 1 nodes of a tree before you visit the
depth 2 nodes and so on.

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

The code looks like this:

Node>>levelOrderDo: aBlock
    I queue I
    queue := OrderedCollection with: self.
    [queue empty] whileFalse:
        [I current I
         current := queue removeLast.
         aBlock value: current.
         queue addAllFirst: current children]
You can implement a priority queue with a SortedCollection using `add:` and `removeFirst;`, instead of `addFirst:` and `removeLast:`.

I can vividly remember the moment I became a computer scientist. I was in a first data structure class taught by Andrzej Proskurowski at the University of Oregon. Gray light through the windows washed most of the color out of the room (we are talking about Eugene, Oregon, here). I was just getting comfortable with data structures as a concept separate from programming but I was still squirming a bit sitting there, since Andrzej was a pretty aggressive professor.

Andrzej had the size and energy of a hummingbird but was muscled like a gymnast. He had a thick black goatee and an even thicker Polish accent. He kept us all on our toes with the simple trick of calling everyone by name after hearing the names exactly once. He had just presented a linked list implementation of queues in Pascal using a header record. I followed pretty well, a first for me, when I got a conviction that there was a shorter implementation.

I could see nothing but my notebook as I scrambled to code in my head, and then on paper, a version that used a footer record instead. Sure enough, I could slice one line out of one of the routines. After class, I hustled over to the computer center to try it out. Bingo! It ran. I rushed over to Andrzej's office to show him my gem. He was skeptical at first, but we went over it and he congratulated me on my success. It was the first time I'd spoken to a professor one on one. I was overwhelmed.

I have since given up computer science for software engineering, but writing this has given me a renewed sense of how important that little bit of transformation was for me.

## Searching Literal

* How do you search for one of a few literal objects known when you write the code?

If Smalltalk had a case statement, you would be tempted to write
```perl
Character>>isVowel
    case self asLowercase of
        $a:
        $e:
        $i:
        $o:
        $u: ^true
    otherwise: ^false
```

(I'm suggesting case statement syntax. A Choosing Message is almost always better than hard coded cases, anyway.)

Since Smalltalk doesn't have a case statement, you generally have to resort to Boolean or conditional logic:

```perl
Character>>isVowel
    I lower I
    lower := self asLowercase.
    ^lower = $a I (lower = $e) I (lower = $i) I (lower = $o)
    I (lower = $u)
```

Pretty ugly, eh? Not as bad as:

```perl
Character>>isVowel
    self = $a I (self = $A) ifTrue: [^true].
    self = $e I (self = $E) ifTrue: [^true].
    self = $i I (self = $I) ifTrue: [^true].
    self = $o I (self = $O) ifTrue: [^true].
    self = $u I (self = $U) ifTrue: [^true].
    ^false
```
Because Strings are literals, you can use the collection protocol to implement the same thing much more compactly:

```python
Character>>isVowel
    ^'aeiou' includes: self asLowercase
```

* Ask a literal `Collection` if it includes the element you are seeking.

You can do the same thing with `Symbols`:

```python
Style>>isFancy: aSymbol
    ^#(bold italic) includes: aSymbol
```

This is not a trick that comes up every day, but used occasionally it can save you a few lines of code.

## Lookup Cache

* How do you optimize complex `Detect` or `Select/Reject` loops?

The simplest solution is just to keep your code in its original form. Sometimes, what you are doing is looking up an element by a simple attribute:

```python
childNamed: aString
    ^self children detect: [:each | each name = aString]
```
Sometimes, you are computing subsets of the elements in a collection:

```perl
childrenWithHairColor: aString
    ^self children select: [:each | each hairColor = aString]
```

These are simple to write and simple to read. This first time you need
code like this, you should definitely write it in terms of Enumeration.

For large collections or frequently computed expressions, this kind of
computation can be a performance bottleneck. If you measure a problem with
one of these expressions, you may be able to cache the result of computation
and reuse it rather than recomputing it.

As with all caches, you will only be able to do this if you can keep the
contents of the cache synchronized with changes to the collection and its
elements.

* Prepend "lookup" to the name of the expensive search or filter method. Add an instance variable holding a Dictionary to cache results. Name the variable by appending "Cache" to the name of the search. Make the parameters of the search the keys of the Dictionary and the results of the search the values.

The first example above turns into a variable called "nameCache."
First, we change the original method to:

```perl
lookupChildNamed: aString
    ^self children detect: [:each | each name = aString]
```

Assuming the variable holding the lookup cache is initialized (see
Explicit Initialization and Lazy Initialization), we rewrite
"childNamed:" as:
```
childNamed: aString
    ^nameCache
    at: aString
    ifAbsentPut: [self lookupChildNamed: aString]
```

VisualWorks doesn't implement `at`: `ifAbsentPut`: and VisualAge takes an object as the second parameter, not a `Block`, so you have to write:

```
childNamed: aString
    ^nameCache
    at: aString
    ifAbsent:
        [nameCache
            at: aString
            put: (self lookupChildNamed: aString)]
```

The second example above has `collections` as the values in the `Dictionary` instead of single objects, but other than that, the pattern plays out similarly:

```
lookupChildrenWithHairColor: aString
    ^self children select: [:each | each hairColor = aString]
childrenWithHairColor: aString
    ^hairColorCache
    at: aString
    ifAbsentPut: [self lookupChildrenWithHairColor:
        aString]
```
# Parsing Stream

* How do you write a simple parser?

You will probably have to write simple parsers in Smalltalk. I don't mean the kind that computer scientists love, with lots of Ls and Rs and numbers in their name. I mean the simple kind, where each line has a keyword and then a bunch of information, different depending on the keyword.

One simple way to structure code like this is by grabbing a line at a time and parsing it.

```perl
parse: aStream
[aStream atEnd] whileFalse: [self parseLine: aStream
nextLine]

parseLine: aString
  I reader I
  reader := ReadStream on: aString.
  keyword := reader nextWord.
  keyword = 'one' ifTrue: [self parseOne: reader].
  keyword = 'two' ifTrue: [self parseTwo: reader].
  ...
```

This leads to code that creates Strings and Streams all over the place. Something (a String or Stream) has to be passed to each method. If the methods are deeply nested, that extra parameter becomes tedious. It is error-prone, too, since it is easy to forget whether you are dealing with a String or a Stream.

In many cases, having many methods share the same instance variable is dangerous, especially if it is an object that will be side effected by many methods. A change in one method is likely to affect others inadvertently. In the case of parsing, though, the danger is minimized because of the simple nature of the control flow.

* *Put the Stream in an instance variable. Have all parsing methods work from the same Stream.*

Using this pattern, the code above looks like:
```java
parse: aStream
    reader := aStream. "Reader is now an instance
variable."
    [reader atEnd] whileFalse: [self parseLine]
```

```java
parseLine
    keyword := reader nextWord.
    keyword = 'one' ifTrue: [^self parseOne].
    keyword = 'two' ifTrue: [^self parseTwo].
    ...
```

The lack of parameters cleans up the code considerably. Each parsing method has to be careful to leave the Parsing Stream in a known state so the other methods can simply assume where they are in the String.

The "case statement," formed by the conditionals in parseLine above, leads some folks to want a "real" case statement in Smalltalk. For me, having to write the code above once a year just isn't sufficient justification for adding a new language feature.

## Concatenating Stream

> You may be collecting results in a Collecting Temporary Variable (p. 105). You
> may be collecting results over several methods in a Collecting Parameter (p. 75).

* How do you concatenate several Collections?

Concatenation is a simple way to join several Collections. When you have
lots of Collections, though, it can be slow because the objects in the first
Collection are copied once for each Collection that is concatenated.

Streams provide a way out of this dilemma. Streams are careful not to
copy their contents many times, even as the Collection they are streaming over
gets larger.

* Use a Stream to concatenate many Collections.

<figure><img src="image_20.png" /></figure>
I ran a quick benchmark to see how significant the difference was
between Collection concatenation and Streams. I ran the following
code, which concatenates one thousand Strings:

100 timesRepeat:
    [result := String new.
    1000 timesRepeat: [result := result, 'abcdefg']]

It took 53 seconds to run. Then I ran the Stream version:

100 timesRepeat:
    [writer := WriteStream on: String new.
    1000 timesRepeat: [writer nextPutAll: 'abcdefg'].
    writer contents]]

It took 0.9 seconds to run. The difference is a factor of almost 60.

Sometimes, you will use Concatenating Stream not because it is
your choice, but because you have to fit into other code that
already uses it. The most common example is specializing object
printing by overriding printOn:.
6

Classes

There is probably no coding decision with more effect on the quality of your code than names you give your classes. If computers were the only audience for code, we could just call them C1, C2, C3, and have done. The expensive reader is not the computer, it is other people.

Naming classes is your biggest billboard for communicating about your system. The first thing readers will look at when they look at your code is the names of the classes. Those names will go beyond your code. Insidiously, they leak into everyday conversation—and not just for developers. Ten years down the road, you will hear users who know nothing about programming using the class names you chose.

Good class names provide insight into the purpose and design of a system. They reveal underlying metaphors. They communicate themes and variations. They break the system into parts and show how the parts get put back together.

Great naming is an art and will always remain so (just ask Madison Avenue). Good naming is in the reach of everyone. Avoiding obvious mistakes and producing names that work together will boost your class names above average.
## Simple Superclass Name

* What do you call a class that is expected to be the root of an inheritance hierarchy?

All naming decisions have several constraints in common. You want names that are as short as possible, so they are easy to type, format, and say. At the same time, you want to convey as much information as possible in each name, so readers will not have to carry as much knowledge in their heads. You want names that are familiar, to take advantage of knowledge readers already have via metaphor or analogy. However, you want names that are unique, so that others who are also choosing names will not accidentally choose names that interfere with yours.

The first rule I follow is no abbreviations. Abbreviations optimize typing (a 10-100 times in 20 years task) over reading (a 1000-10000 times in 20 years task). Abbreviations make the interpretation of a name a two step process—what do the letters stand for and then what do those words mean. The class and method naming patterns here will produce names that you should never have to abbreviate.

Naming the root class of a large hierarchy is a momentous occasion. People will be using the words you choose in their conversation for the next 20 years. You want to be sure you do it right.

Unfortunately, many people get all formal when they go to name a super-class. Just calling it what it is isn't enough. They have to tack on a flowery, computer science-y, impressive sounding, but ultimately meaningless word, like Object, Thing, Component, Part, Manager, Entity, or Item.

You're creating a vocabulary, not writing a program. Be a poet for a moment. The simple, the punchy, the easily remembered will be far more effective in the long run than some long name that says it all, but in such a way that no one wants to say it at all.

* Name a superclass with a single word that conveys its purpose in the design.

Here are some good examples in the image:
* Number
* Collection
* Magnitude
* Model

FORWARD

*You may create variations on this class, each with a Qualified Subclass Name (p. 169).*

BACK

## Qualified Subclass Name

*You have created a Simple Superclass Name (p. 168).*

* What do you name a new subclass?

One way to name classes is to give each a unique name, indicative of its purpose. Unique names give you the opportunity to convey a lot of information without creating names that are long and unwieldy.

This is exactly the right thing to do if the names are in common use. Array is a subclass of Collection because lots of software engineers guess correctly about the nature of the class by reading “Array.” Number is a subclass of Magnitude because Number-ness is far more important to communicate than Magnitude-ness. String is a subclass of Collection because everyone knows what a String is.

In general, if I am using inheritance strictly for code sharing, but the role of the subclass is different than the role of the superclass, I go back to Simple Superclass Name.

More often, the inheritance structure of your code is important for a reader to understand, particularly where a subclass is both conceptually a variation on the superclass and they share implementation. The two pieces of information you need to communicate are:

* how the new class is the same; and

* how the new class is different.

You can communicate how the new class is the same by naming some superclass. It need not be the immediate superclass, if some distant ancestor communicates more clearly.
You can communicate how the new class is different by finding a word that accurately highlights the reason the new class isn't just the superclass.

* *Name subclasses in your hierarchies by prepending an adjective to the superclass name.*

For example:

* `OrderedCollection` is a `Collection` in which elements are Ordered.

* `SortedCollection` is a `Collection` in which elements are Sorted. Even though `SortedCollection` subclasses `OrderedCollection`, you wouldn't call it `SortedOrderedCollection`. The choice to subclass `OrderedCollection` is strictly for implementation reasons, not because the two collections play similar roles.

* `LargeInteger` is an `Integer` that takes many bits to represent.
7

Formatting

No other topic generates more heat and less light than code
formatting. Everybody has their own style and attempts to impose
another style are met with ferocious resistance. So, why am I will-
ingly sticking my head into this buzz saw?

The first reason is “because it is there.” I want to push pat-
terns to their limit, to see how well they apply to a detail-oriented,
exception-ridden, and emotion-filled topic. I wrote these patterns
over the course of a couple of months. As new special cases came up,
I either had to modify the patterns, add a new pattern, or format my
code according to the existing patterns. Before long, I no longer was
finding cases where I had to change the patterns. I am quite pleased
that all of formatting in Smalltalk fits into ten patterns.

The second reason is “because it is important.” Not necessari-
ly formatting code according to these patterns but formatting them
according to some set of consistent rules gives a team a smoothness
to their interaction. If everybody formats the same way, then
reviews and code transfer are never delayed while someone “cleans
up” the code. Done right, formatting can convey a lot of information
about the structure of code at a glance.
The third reason is to advance the discussion of formatting. Stating the rules as patterns makes my goals and tradeoffs explicit. If you have a different style, you can use these patterns as an example to cast your own rules as patterns. Then you can compare, explicitly, what problems each set of patterns solves and what problems each ignores.

The priorities of these patterns are:

1. To make the gross structure of the method apparent at a glance. Complex messages and blocks, in particular, should jump out at the reader.

2. To preserve vertical space. There is a huge difference between reading a method that fits into the text pane of a browser and reading one that forces you to scroll. Keeping methods compact vertically lets you have smaller browsers and still be able to read methods without scrolling. This reduces window management overhead and leaves more screen space for other programming tools.

3. To be easy to remember. I have seen style guides that have 50-100 rules for formatting. Formatting is important but it shouldn't take that much brain power.

There are many styles of Smalltalk coding for which these formatting patterns would be a disaster. Long methods and methods that use complex expressions look terrible formatted this way. However, thorough use of Composed Method and Explaining Temporary Variable, along with the attitude that you are writing for a reader and not the computer, will go a long way towards helping you produce code that is simple to format and simple to read.

## Inline Message Pattern

> You are about to write a method for an Intention Revealing Selector (p. 49).

* How do you format the message pattern?

One alternative is to write the keyword/argument pairs one per line. This makes it easy to see what the selector of the method is by reading straight down from the top left corner. However, this style of formatting will often take up three or four lines of vertical space. Composed Methods are generally only a few lines long. It seems a waste of space to have more introduction than content.

Another reason for lining up the keywords vertically is that early text editors did not have line wrapping, so if you wanted to see all the parameters, you had to scroll horizontally. All current Smalltalks have line wrapping avail-
able in the source code editor, so all arguments are available regardless of window size or message pattern width.

The problem of reading the selector as a whole is solved by the browser. You never look at a method as a raw piece of text. Methods always appear in the context of a browser. The selector is always presented near the method. If you forget what method you are working on, a quick glance above the method will answer your question.

By saving the vertical space otherwise taken up by the message pattern, you can quickly scan many methods in a smaller browser than is otherwise possible. This allows you to have more information on the screen at the same time, if it is useful. There is a big difference between browsing a program without every having to scroll the text of a method and browsing where you are constantly scrolling.

* Write the message pattern without explicit line breaks.

Here is a message pattern formatted with this pattern:

from: fromInteger to: toInteger with: aCollection startingAt: startInteger

I've seen this formatted like this:

from: fromInteger
to: toInteger
with: aCollection
startingAt: startInteger

or worse:
* from: fromInteger

* to: toInteger

* with: aCollection

* startingAt: startInteger

Both of these spend vertical space, increasing the chance that you won't be able to see the body of the method (the part that matters and the part that is likely to be surprising) without scrolling.

**Use Type Suggesting Parameter Names (p. 174) for parameters.**

FORWARD

BACK

## Type Suggesting Parameter Name

**You are writing an Inline Message Pattern (p. 172). You might be completing a Double Dispatch (p. 55).**

* What do you call a method parameter?

There are two important pieces of information associated with every variable—what messages it receives (its type) and what role it plays in the computation. Understanding the type and role of variables is important for understanding a piece of code.

Keywords communicate their associated parameter's role. Since the keywords and parameters are together at the head of every method, the reader can easily understand a parameter's role without any help from the name.

Smalltalk doesn't have a strong notion of types. The set of messages sent to a variable appears nowhere in the language or programming environment. Because of this lack, there is no direct way to communicate types.

Classes sometimes play the role of types. You would expect a Number to be able to respond to messages like +, -, *, and /; or a Collection to do: and includes:

* Name parameters according to their most general expected class, preceded by "a" or "an." If there is more than one parameter with the same expected class, precede the class with a descriptive word.
An Array that requires Integer keys names the parameters to
at:put: as

at: anInteger put: anObject

A Dictionary, where the key can be any object, names the para-
meters:

at: keyObject put: valueObject

FORWARD

After you have named the parameters, you are ready to write the method. You
may have to declare Role Suggesting Temporary Variable Names (p. 110). You
may need to format an Indented Control Flow (p. 175). You may have to use a
Guard Clause (p. 178) to protect the execution of the body of the method.

Indented Control Flow

* How do you indent messages?

The conflicting needs of formatting to produce both few lines and short
lines is thrown in high relief with this pattern. The only saving grace is that
Composed Method creates methods with little enough functionality that you
never need to deal with hundreds or thousands of words in a method.

One extreme would be to place all the keywords and arguments on the
same line, no matter how long the method. This minimizes the length of the
method but makes it difficult to read.

If there are multiple keywords to a message, the fact that they all appear
is important to communicate quickly to a scanning reader. By placing each
keyword/argument pair on its own line, you can make it easy for the reader to
recognize the presence of complex messages.
Arguments do not need to be aligned, unlike keywords, because readers seldom scan all the arguments. Arguments are only interesting in the context of their keyword.

* Put zero or one argument messages on the same lines as their receiver. For messages with two or more keywords put each keyword/argument pair on its own line, indented one tab.

Here are some zero and one argument messages formatted with Indented Control Flow:

foo isNil
2 + 3
a < b ifTrue: [...]

Here are some two argument messages formatted with Indented Control Flow:

a < b
  ifTrue: [...]
  ifFalse: [...]
array
  at: 5
  put: #abc

Many people have complex exceptions for formatting control statements, like `ifTrue:` and `whileTrue:`. One of the things I really like about this pattern is that it gives reasonable results while treating conditional statements as just another message send (which they are, after all).

Formatting code like this makes reading the whole selector easy. You can easily read that the message in this example is `#copyFrom:to:with:startingAt:`
aCollection
copyFrom: 1
to: aString size
with: aString
startingAt: 1

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

**Rectangular Block (p. 177) formats blocks. Guard Clause (p. 178) prevents indenting from marching across the page.**

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

## Rectangular Block

*You are writing an expression with Indented Control Flow (p. 175).*

* How do you format blocks?

Smalltalk distinguishes between code that is executed immediately upon the activation of a method and code whose execution is deferred. To read code accurately, you must be able to quickly distinguish which code in a method falls into which category.

Code should occupy as few lines as possible, consistent with readability. Short methods are easier to assimilate quickly and they fit more easily into a browser. On the other hand, making it easy for the eye to pick out blocks is a reasonable use of extra lines.

One more resource we can bring to bear on this problem is the tendency of the eye to distinguish and interpolate vertical and horizontal lines. The square brackets used to signify blocks lead the eye to create the illusion of a whole rectangle even though one isn't there. Therefore:

* Make blocks rectangular. Use the square brackets as the upper left and bottom right corners of the rectangle. If the statement in the block is simple, the block can fit on one line. If the statement is compound, bring the block onto its own line and indent.

Here are a couple of one line blocks:
```kotlin
ifTrue: [self recomputeAngle]
ifTrue: [^angle * 90 + 270 degreesToRadians]
```

Here is a block that takes two lines because it contains two statements:

```kotlin
ifTrue:
    [self clearCaches.
     self recomputeAngle]
```

Here is a block that takes two lines because it contains a two parameter message:

```kotlin
ifTrue:
    [self
     at: each
     put: 0]
```

## Guard Clause

BACK

> You are writing an expression with an Indented Control Flow (p. 175).

How do you format code that shouldn't execute if a condition holds?

In the bad old days of Fortran programming, when it was possible to have multiple entries and exits to a single routine, tracing the flow of control was a nightmare. Which statements in a routine got executed, and when, was impossible to determine statically. This lead to the commandment "Every routine shall have one entry and one exit."
Smalltalk labors under few of the same constraints of long ago Fortran, but the prohibition against multiple exits persists. When routines are only a few lines long, understanding flow of control within a routine is simple. It is the flow between routines that becomes the legitimate focus of attention.

Multiple returns can simplify the formatting of code, particularly conditionals. What's more, the multiple return version of a method is often a more direct expression of the programmer's intent. Therefore:

* Format the one-branch conditional with an explicit return.

Let's say you have a method that connects a communication device only if the device isn't already connected. The single exit version of the method might be:

```python
connect
    self isConnected
    ifFalse: [self connectConnection]
```

You can read this as "If I am not already connected, connect my connection." The guard clause version of the same method is:

```python
connect
    self isConnected ifTrue: [^self].
    self connectConnection
```

You can read this as "Don't do anything if I am connected. Connect my connection." The guard clause is more a statement of fact, or an invariant, than a path of control to be followed.
## Conditional Expression

* How do you format conditional expressions where both branches assign or return a value?

Most programming languages make a distinction between statements that work solely by side effect and expressions that return values. For example, control structures in C and Pascal work only by controlling how other statements execute.

In Smalltalk, there are no pure statements. All control structures are implemented in terms of messages, and all messages return values. This leads to the possibility of using the value of control structures.

Programmers new to Smalltalk are likely to be surprised the first time they encounter loops or conditionals used as an expression. New Smalltalkers are likely to write:

```self
isInitialized
    ifTrue: [cost := self calculateCost]
    ifFalse: [cost := 0]
```

These expressions can be translated into the following without changing the meaning:

```self
cost := self isInitialized
    ifTrue: [self calculateCost]
    ifFalse: [0]
```

Is the simpler form worth the possibility of confusion for beginners? It more directly communicates the intent of the expression. You don't mean "There are two paths of expression, one of which sets the value of cost to the result of sending myself calculateCost and the other of which sets the value of cost to 0." You mean, "Set cost to one of two values, either the result of sending myself calculateCost or 0."
* Format conditionals so their value is used where it clearly expresses the intent of the method.

Assignment and return are often found in both branches of a conditional. Look for opportunities to factor both to the outside of the conditional.

Here is an example of a return on both branches of a conditional:

```kotlin
cost
    self isInitialized
        ifTrue: [^self calculateCost]
        ifFalse: [^0]
```

If I write code like this, I don't mean, "Here are two alternative paths of execution." I mean, "Here are two alternative values to be returned." Thus, a Conditional Expression expresses my intent more clearly:

```kotlin
cost
    ^self isInitialized
        ifTrue: [self calculateCost]
        ifFalse: [0]
```

I commonly see code in which both sides of a conditional expression evaluate to a Boolean. Start with this:

```kotlin
aCollection empty
    ifTrue: [empty := true]
    ifFalse: [empty := false]
```
Using Conditional Expression we first factor out the assignment:

empty := aCollection empty
ifTrue: [true]
ifFalse: [false]

We can go a step further and eliminate the conditional entirely. The
following code is equivalent to the preceding:

empty := aCollection empty

BACK

You may be able to express one or both branches of the conditional more explicitly by using a Composed Method (p. 21).

## Simple Enumeration Parameter

* What do you call the parameter to an enumeration block?

It is tempting to try to pack as much meaning as possible into every
name. Certainly, classes, instance variables, and messages deserve careful
attention. Each of these elements can communicate volumes about your intent
as you program.

Some variables just don't deserve such attention. Variables that are
always used the same way, where their meaning can be easily understood from
context, call for consistency over creativity. The effort to carefully name such
variables is wasted because no non-obvious information is communicated to
the program. They may even be counter productive, if the reader tries to
impute meaning to the variable that isn't there.

* Call the parameter "each." If you have nested enumeration blocks, append a descriptive word to all parameter names.
For example, the meaning of "each" in

``` Groovy
self children do: [:each | self processChild: each]
```

is clear. If the block is more complicated, each may not be descriptive enough. In that case, you should invoke Composed Method to turn the block into a single message. The Type Suggesting Parameter in the new method will clarify the meaning of the object.

The typical example of nested blocks is iterating over the two dimensions of a bitmap:

``` Groovy
1 to: self width do:
    [:eachX |
    1 to: self height do:
        [:eachY | ...]]
```

Nested blocks that iterate over unlike collections should probably be factored with Composed Method.

**You may need Composed Method to simplify the enumeration block.**

BACK

## Cascade

* How do you format multiple messages to the same receiver?

The simplest solution is to just repeat the expression that created the receiver. Such code looks like this:

``` Groovy
self listPane parent color: Color black.
self listPane parent height: 17.
self listPane parent width: 11.
```
For complex expressions, the first simplification is to use an Explaining Temporary Variable to hold the value of the expression:

```
| parent |
parent := self listPane parent.
parent color: Color black.
parent height: 17.
parent width: 11.
```

One of Smalltalk's few syntactic quirks is a solution to this problem. Rather than having to repeat an expression or create a temporary variable to hold the expression, Smalltalk lets you say at the end of one message "Here's another message to the same receiver."

* Use a Cascade to send several messages to the same receiver. Separate the messages with a semicolon. Put each message on its own line and indent one tab. Only use Cascades for messages with zero or one argument.

The code above becomes:

```
self listPane parent
    color: Color black;
    height: 17;
    width: 11
```

Whether or not you use a Cascade is really a matter of intent. If you want to communicate "Here are a bunch of messages all going to the same object," that's a good time to use a Cascade. If you just happen to be sending messages to the same object, but it's not really part of the essence of the code that the two messages are going to the same object, don't use a Cascade.

One confusion that sometimes arises about Cascade is if the initial expression is complex, where do the cascaded messages get sent?
For example, in:

OrderedCollection new
    add: 5;
    add: 10

the indentation cues you that both adds get sent to the new OrderedCollection, not the class itself. Here's the rule: All subsequent messages in a Cascade go to the same receiver as the first message in the cascade (in this case, #add:). Any preceding parts of the expression that got you the receiver are irrelevant.

The restriction that Cascades only be used with zero or one argument messages comes from the difficulty in visually parsing Cascades with varying numbers of arguments. In the example above, what if you could send height:width: as a single message? Using Cascade, the code would look like:

self listPane parent
    color: Color black;
    height: 17
    width: 11

At a glance, you can't tell whether height and width are set separately or together. The readability gains of a Cascade are quickly lost if you have to spend any time figuring out the messages that are sent. Fortunately, most times messages go to the same receiver (especially more than two), the messages are simple.

**You may have to use Yourself (p. 186) if you are using the value of a Cascade.**
<figure><img src="image_23.png" /></figure>

## Yourself

You need to use the value of a Cascade (p. 183).

* How can you use the value of a Cascade if the last message doesn't return the receiver of the message?

This has got to be the number one confusing method in all of Smalltalk. There it is in Object, where every new Smalltalker stumbles across it:

```
Object>>yourself
^self
```

Or, if the programmer was really clever (and didn't know about Interesting Return Value):

```
Object>>yourself
```

What's going on?

Let's say you want to add a bunch of elements to an OrderedCollection. `Collection>>add:` anObject is defined to return anObject, not the receiver of the message. If you want to assign the Collection to a variable:

```
all := OrderedCollection new
    add: 5;
    add: 7
```
will result in the value of all being 7. There are two solutions to this problem.
The first is to put the variable assignment in parentheses:

```
(all := OrderedCollection new)
    add: 5;
    add: 7
```

* When you need the value of a Cascade and the last message does not return the receiver, append the message "yourself" to the Cascade.

Our example becomes:

```
all := OrderedCollection new
    add: 5;
    add: 7;
    yourself
```

Sending `yourself` returns the receiver, the new instance of OrderedCollection. That's the object that gets assigned to the variable.

I've seen folks become defensive about `yourself`, tacking it onto every Cascade they write. You shouldn't do this. `yourself` is there to communicate to your reader that you really want the value of the receiver used, not the result of sending a message. If you aren't using the value of a Cascade, don't use `yourself`. For example, I wouldn't use it in `Point>>printOn:`, because I don't assign the value of the Cascade to a variable or return it as the value of the method.
```kotlin
Point>>printOn: aStream
aStream
    print: self x;
    nextPut: $@;
    print: self y
```

Having written this, I'm not sure why I prefer Cascades to the parenthesized format. Perhaps it's because there is a big psychological difference in parsing a method with parentheses and one without. If I can avoid parentheses and still have a method that reads clearly, I will.

Another use of "yourself" is with `#inject:into:`. Suppose you want to put all the children of a collection of parents together in a Set. You might be tempted to write:

```kotlin
parents
    inject: Set new
    into: [:sum :each | sum addAll: each children]
```

But this wouldn't work because the result of sending `#ADDALL:` is the argument (in this case the children), not the receiver. To get this to work as expected, you have to write:

```kotlin
parents
    inject: Set new
    into: [:sum :each | sum addAll: each children; yourself]
```

## Interesting Return Value

* When do you explicitly return a value at the end of a method?
All messages return a value. If a method does not explicitly return a value, the receiver of the message is returned by default. This causes some confusion for new programmers, who may be used to Pascal's distinction between procedures and functions, or C's lack of a definition of the return value of a procedure with no explicit return. To compensate, some programmers always explicitly return a value from every method.

The distinction between methods that do their work by side effect and those that are valuable for the result they return is important. An unfamiliar reader wanting to quickly understand the expected use of a method should be able to glance at the last line and instantly understand whether a useful return value is generated or not. Therefore:

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

For example, consider the implementation of topComponent in VisualWorks. Visual components form a tree, with a ScheduledWindow at the root. Any component in the tree can fetch the root by sending itself the message "topComponent." VisualPart (the superclass of interior nodes and leaves) implements this message by asking the container for its topComponent:

VisualPart->topComponent
^container topComponent

ScheduledWindow implements the base case of the recursion by returning itself. The simplest implementation would be to have a method with no statements. It would return the receiver. However, using Interesting Return Value, because the result is intended to be used by the sender, it explicitly returns "self."

ScheduledWindow->topComponent
^self
*This page intentionally left blank*
Chapter

8

Development
Example

In this chapter, I will pretend to develop a piece of
software guided by the Best Practice Patterns. It will
likely seem incredibly slow to you, since I won't write
more than a couple of words of code without pointing out
another pattern. Not to worry, once you get used to the
patterns you don't really think of them individually. You
build higher levels of structure in your mind that let you
just write clean code quickly and without thinking con-
sciously of the smaller steps, much as you can speak
without consulting a grammar book.

**Problem**

The problem we will solve is representing multi-currency monetary values. It's not as simple as it might seem. There are lots of unit-value computations in the world. Any time you use a number, you generally have at least an implied set of units behind it, whether inches, pixels, or kilograms. Some units can be freely converted into others, like pounds to kilograms. Others just don't make any sense. If you add four meters to two grams you
should get an error. One simplifying assumption that makes unit-values easy to program is that for conversions that make sense, there is a single, immutable conversion ratio. You don't have to go look up the New York spot quote on pound to kilograms every morning.

Money is different. There is no single conversion rate. There isn't really a single sequence of conversion rates. Sometimes, you want to answer questions like, “How does the value of my portfolio differ if I liquidate it in Hong Kong or Zurich?” This need for flexibility is the primary driving force in designing objects to represent currency.

Start

The first object we'll give the Simple Superclass Name of Money. It represents a value in a single currency.

* Class: Money
* superclass: Object
* instance variables: amount currency

The variable with the Role Suggesting Instance Variable Name “amount” will hold any old Number. This lets us defers issues of numerical accuracy and stability to the Number classes. If you want a super accurate but slow Money, you can make the Amount a FixedPoint. If you want less accuracy but more speed, you can use a Double. As long as the amount responds to number-like messages, Money won't care.

The variable “currency” will hold Symbol for now, the name of a currency. Currency traders use standard three letter abbreviations for the currencies of the world—USD for United States Dollars, for example. A complete currency system needs a real Currency object, because different currencies act different computationally, but for now all we care about is whether two currencies are equal or not.

How do we create a Money? We need a Constructor Method.
```kotlin
Money class>>amount: aNumber currency: aSymbol
    ^self new
        setAmount: aNumber
currency: aSymbol
```

The method communicates the types of its parameters with Type Suggesting Parameter Names. The body of the method uses Indented Control Flow to make it clear to the reader that the Constructor Parameter Method takes two arguments. Constructor Methods also always have an Interesting Return Value.

Now we need to set the instance variables to the objects provided to the Constructor Method. We write a Constructor Parameter Method:

```kotlin
Money>>setAmount: aNumber currency: aSymbol
    amount := aNumber.
currency := aSymbol
```

If we want to check that our code works, we will need a Debug Print Method.

```kotlin
Money>>printOn: aStream
    aStream
        print: amount;
        space;
nextPutAll: currency
```
Note that this method uses a Cascade to show that three message are being sent to the same Stream.

Now we can try out the code in a workspace (the stuff in italics is what prints as a result):

Money
  amount: 5
  currency: #USD 5 USD

## Arithmetic

How do we add two Moneys together? Let's get the simple case right first, where we have the same currency in both Moneys. When you add two Moneys with the same currency together, the resulting Money should have as its amount the sum of the amounts of the first two.

Money>>+ aMoney
  ^self species
    amount: amount + aMoney amount
currency: currency

We need a Getting Method for the variable "amount" for this to work:

Money>>amount
  ^amount

We get the right answer if we're adding dollars to dollars:
```
| m1 m2 |
m1 := Money
    amount: 5
    currency: #USD.
m2 := Money
    amount: 7
    currency: #USD.
m1 + m2 12 USD
```

Change one of the Moneys to a different currency, though, and we get the wrong answer:

```
| m1 m2 |
m1 := Money
    amount: 5
    currency: #USD.
m2 := Money
    amount: 7
    currency: #GBP.
m1 + m2 12 USD
```

Five dollars and seven pounds is not twelve dollars. How are we going to keep the simple `+` protocol for arithmetic and still handle the case where we have multiple currencies? The answer is to introduce an Impostor (a modeling pattern) for a Money that defers exchange rate conversions. We'll give it the Simple Superclass Name of MoneySum.

```
Class: MoneySum
superclass: Object
instance variables: monies
```
The variable with the Role Suggesting Instance Variable Name "monies" will hold a Collection of Moneys.

We create a MoneySum with a Constructor Method:

MoneySum class>>monies: aCollection
^self new setMonies: aCollection

The collection is passed on to the Constructor Parameter Method:

MoneySum>>setMonies: aCollection
monies := aCollection

We'll add a Debug Print Method to MoneySum so we can check our
results:

MoneySum>>printOn: aStream
monies do:
    [each |
aStream
    print: each;
    nextPutAll: ' + '].
aStream skip: -3

We used a basketful of patterns in this method: Direct Variable Access, Role Suggesting Parameter Name, Simple Enumeration Parameter, Rectangular Block, Indented Control Flow, and Do.

With MoneySum in hand, we can modify Money>>+ to return a
MoneySum if the two currencies don't match:
```pascal
Money>>+ aMoney
    ^currency = aMoney currency
    ifTrue:
        [self species
            amount: amount + aMoney amount
currency: currency]
    ifFalse:
        [MoneySum monies: (Array
            with: self
            with: aMoney)]
```

We need a Getting Method for Money's currency:

```pascal
Money>>currency
    ^currency
```

Now our multi-currency example works:

```pascal
| m1 m2 |
m1 := Money
    amount: 5
currency: #USD.
m2 := Money
    amount: 7
currency: #GBP.
m1 + m2 5 USD + 7 GBP
```

Just to check, the single currency example works, still:
```
| m1 m2 |
m1 := Money
    amount: 5
    currency: #USD.
m2 := Money
    amount: 7
    currency: #USD.
m1 + m2 12 USD
```

## Integration

For a MoneySum to truly be an Impostor for a Money, it has to support all the same messages. All the combinations of Moneys and MoneySums have to work together. We will use Double Dispatch to implement this. Double Dispatch states: "Send a message to the argument. Append the class name of the receiver to the selector. Pass the receiver as an argument." Money addition becomes:

```
Money >> + aMoney
    ^aMoney addMoney: self
```

The old `Money >> +` becomes `Money >> addMoney`:

```
Money >> addMoney: aMoney
    ^currency = aMoney currency
    ifTrue:
        [self species
            amount: amount + aMoney amount
            currency: currency]
    ifFalse:
        [MoneySum monies: (Array
            with: self
            with: aMoney)]
```
MoneySum arithmetic follows the Double Dispatch pattern, too:

```perl
MoneySum>> + aMoney
    ^aMoney addMoneySum: self
```

If a MoneySum is adding a Money, it should produce a new MoneySum with the Money added to the list of Monies:

```perl
MoneySum>>addMoney: aMoney
    ^self species monies: (monies copyWith: aMoney)
```

Now we can send `+` to a Money with a MoneySum as argument:

```
| m1 m2 |
m1 := Money
    amount: 5
currency: #USD.
m2 := Money
    amount: 7
currency: #GBP.
m1 + (m2 + m1) 5 USD + 7 GBP + 5 USD
```

To complete the Double Dispatch, we have to implement `addMoneySum`: in `Money` and `MoneySum`. The implementation in `Money` is simple, we just turn around and send `addMoneySum` to the `MoneySum`, trusting the existing implementation to work:

```perl
Money>> addMoneySum: aMoneySum
    ^aMoneySum addMoney: self
```
We can test this:

| m1 m2 |
m1 := Money
    amount: 5
currency: #USD.
m2 := Money
    amount: 7
currency: #GBP.
m1 + m2 + m1 7 GBP + 5 USD + 5 USD

The final combination is adding a MoneySum to a MoneySum. We do this
by concatenating the monies of both of them:

MoneySum>>addMoneySum: aMoneySum
    ^MoneySum monies: monies, aMoneySum monies

We can test this:

| m1 m2 |
m1 := Money
    amount: 5
currency: #USD.
m2 := Money
    amount: 7
currency: #GBP.
(m1 + m2) + (m1 + m2) 7 GBP + 5 USD + 7 GBP + 5 USD
## Summary

We used these patterns in the code above:

<table><thead><tr><td>Pattern</td><td>Example</td></tr></thead><tbody><tr><td>Simple Superclass Name</td><td>Money, MoneySum</td></tr><tr><td>Constructor Method</td><td>MoneySum class&gt;&gt;monies:</td></tr><tr><td>Constructor Parameter Method</td><td>MoneySum&gt;&gt;setMonies:</td></tr><tr><td>Common State, Role</td><td>Money "currency"</td></tr><tr><td>Suggesting Instance Variable Name</td><td></td></tr><tr><td>Intention Revealing Selector</td><td>Money&gt;&gt;+</td></tr><tr><td>Getting Method</td><td>Money&gt;&gt;currency</td></tr><tr><td>Composed Method</td><td>Money class&gt;&gt;amount:currency:</td></tr><tr><td>Decomposing Message</td><td>Money class&gt;&gt;amount:currency: sending #setAmount:currency:</td></tr><tr><td>Choosing Message</td><td>addMoney:, addMoneySum:</td></tr><tr><td>Dispatched Interpretation, Double Dispatch</td><td>Money&gt;&gt;addMoney:</td></tr><tr><td>Debug Print Method</td><td>Money&gt;&gt;printOn:</td></tr><tr><td>Array</td><td>MoneySum</td></tr><tr><td>Inline Message Pattern</td><td>Money&gt;&gt;setAmount:currency:</td></tr><tr><td>Indented Control Flow</td><td>Money&gt;&gt;addMoney:</td></tr><tr><td>Conditional Expression</td><td>Money&gt;&gt;addMoney:</td></tr><tr><td>Rectangular Block</td><td>Money&gt;&gt;addMoney:</td></tr><tr><td>Direct Variable Access</td><td>Money&gt;&gt;addMoney:</td></tr><tr><td>Type Suggesting Parameter Name</td><td>Money class&gt;&gt;amount: aNumber currency: aSymbol</td></tr><tr><td>Simple Enumeration Parameter</td><td>MoneySum&gt;&gt;printOn:</td></tr><tr><td>Interesting Return Value</td><td>Money&gt;&gt;addMoney:</td></tr></tbody></table>

As you can see from this list, even simple code uses many different techniques to communicate to readers.
*This page intentionally left blank*
A

Quick Reference

<table><tr><td>Composed Method</td><td>How do you divide a program into methods?</td><td>Divide your program into methods that perform one identifiable task. Keep all of the operations in a method at the same level of abstraction. This will naturally result in programs with many small methods, each a few lines long.</td></tr><tr><td>Constructor Method</td><td>How do you represent instance creation?</td><td>Provide methods that create well-formed instances. Pass all required parameters to them.</td></tr><tr><td>Constructor Parameter Method</td><td>How do you set instance variables from the parameters to a Constructor Method?</td><td>Code a single method that sets all the variables. Preface its name with "set", then the names of the variables.</td></tr></table>
<table><tr><td>Shortcut Constructor Method</td><td>What is the external interface for creating a new object when a Constructor Method is too wordy?</td><td>Represent object creation as a message to one of the arguments to the Constructor Method. Add no more than three of these Shortcut Constructor Methods per system you develop.</td></tr><tr><td>Conversion</td><td>How do you convert information from one object's format to another's?</td><td>Convert from one object to another rather than overwhelm any one object's protocol.</td></tr><tr><td>Converter Method</td><td>How do you represent simple conversion of an object to another object with the same protocol but different format?</td><td>Provide a method in the object to be converted that converts to the new object. Name the method by prepending "as" to the class of the object returned.</td></tr><tr><td>Converter Constructor Method</td><td>How do you represent the conversion of an object to another with a different protocol?</td><td>Make a Constructor Method that takes the object to be converted as an argument.</td></tr><tr><td>Query Method</td><td>How do you represent testing a property of an object?</td><td>Provide a method that returns a Boolean. Name it by prefacing the property name with a form of "be"—is, was, will, etc.</td></tr><tr><td>Comparing Method</td><td>How do you order objects with respect to each other?</td><td>Implement "<=" to return true if the receiver should be ordered before the argument.</td></tr><tr><td>Reversing Method</td><td>How do you code a smooth flow of messages?</td><td>Code a method on the parameter. Derive its name from the original message. Take the original receiver as a parameter to the new method. Implement the method by sending the original message to the original receiver.</td></tr></table>
<table><tr><td>Method Object</td><td>How do you code a method where many lines of code share many arguments and temporary variables?</td><td>Create an class named after the method. Give it an instance variable for the receiver of the original method, each argument, and each temporary variable. Give it a Constructor Method that takes the original receiver and the method arguments. Give it one instance method, #compute, implemented by copying the body of the original method. Replace the method with one which creates an instance of the new class and sends it #compute.</td></tr><tr><td>Execute Around Method</td><td>How do you represent pairs of actions that have to be taken together?</td><td>Code a method that takes a Block as an argument. Name the method by appending “During: aBlock” to the name of the first method that needs to be invoked. In the body of the Execute Around Method, invoke the first method, evaluate the block, then invoke the second method.</td></tr><tr><td>Debug Printing Method</td><td>How do you code the default printing method?</td><td>Override printOn: to provide information about an object's structure to the programmer.</td></tr><tr><td>Method Comment</td><td>How do you comment methods?</td><td>Communicate important information that is not obvious from the code in a comment at the beginning of the method.</td></tr><tr><td>Message</td><td>How do you invoke computation?</td><td>Send a named message and let the receiving object decide what to do with it.</td></tr></table>
<table><tr><td>Choosing Message</td><td>How do you execute one of several alternatives?</td><td>Send a message to one of several different kinds of objects, each of which executes one alternative.</td></tr><tr><td>Decomposing Message</td><td>How do you invoke parts of a computation?</td><td>Send several messages to "self."</td></tr><tr><td>Intention Revealing Message</td><td>How do you communicate your intent when the implementation is simple?</td><td>Send a message to "self." Name the message so it communicates what is to be done rather than how it is to be done. Code a simple method for the message.</td></tr><tr><td>Intention Revealing Selector</td><td>What do you name a method?</td><td>Name methods after what they accomplish.</td></tr><tr><td>Dispatched Interpretation</td><td>How can two objects cooperate when one wishes to conceal its representation?</td><td>Have the client send a message to the encoded object. Pass a parameter to which the encoded object will send decoded messages.</td></tr><tr><td>Double Dispatch</td><td>How can you code a computation that has many cases, the cross product of two families of classes?</td><td>Send a message to the argument. Append the class name of the receiver to the selector. Pass the receiver as an argument.</td></tr><tr><td>Mediating Protocol</td><td>How do you code the interaction between two objects that need to remain independent?</td><td>Refine the protocol between the objects so the words used are consistent.</td></tr><tr><td>Super</td><td>How can you invoke super class behavior?</td><td>Invoke code in a super class explicitly by sending a message to "super" instead of "self." The method corresponding to the message will be found in the super class of the class implementing the sending method.</td></tr><tr><td>Extending Super</td><td>How do you add to a super class' implementation of a method?</td><td>Override the method and send a message to "super" in the overriding method.</td></tr></table>
<table><tr><td>Modifying Super</td><td>How do you change part of the behavior of a super class' method without modifying it?</td><td>Override the method and invoke "super", then execute the code to modify the results.</td></tr><tr><td>Delegation</td><td>How does an object share implementation without inheritance?</td><td>Pass part of its work on to another object.</td></tr><tr><td>Simple Delegation</td><td>How do you invoke a disinterested delegate?</td><td>Delegate messages unchanged.</td></tr><tr><td>Self Delegation</td><td>How do you implement delegation to an object that needs reference to the delegating object?</td><td>Pass along the delegating object (i.e. "self") in an additional parameter called "for:"</td></tr><tr><td>Pluggable Behavior</td><td>How do you parameterize the behavior of an object?</td><td>Add a variable that will be used to trigger different behavior.</td></tr><tr><td>Pluggable Selector</td><td>How do you code simple instance specific behavior?</td><td>Add a variable that contains a selector to be performed. Append "Message" to the Role Suggesting Instance Variable Name. Create a Composed Method that simply performs the selector.</td></tr><tr><td>Pluggable Block</td><td>How do you code complex Pluggable Behavior that is not quite worth its own class?</td><td>Add an instance variable to store a Block. Append "Block" to the Role Suggesting Instance Variable Name. Create a Composed Method to evaluate the Block to invoke the Pluggable Behavior.</td></tr><tr><td>Collecting Parameter</td><td>How do you return a collection that is the collaborative result of several methods?</td><td>Add a parameter that collects their results to all of the submethods.</td></tr><tr><td>Common State</td><td>How do you represent state, different values for which will exist in all instances of a class?</td><td>Declare an instance variable in the class.</td></tr></table>
<table><tr><td>Variable State</td><td>How do you represent state whose presence varies from instance to instance?</td><td>Put variables that only some instances will have in a Dictionary stored in an instance variable called "properties." Implement "propertyAt: aSymbol" and "propertyAt:aSymbol put: anObject" to access properties.</td></tr><tr><td>Explicit Initialization</td><td>How do you initialize instance variables to their default value?</td><td>Implement a method "initialize" that sets all the values explicitly. Override the class message new to invoke it on new instances.</td></tr><tr><td>Lazy Initialization</td><td>How do you initialize an instance variable to its default value?</td><td>Write a Getting Method for the variable. Initialize it if necessary with a Default Value Method.</td></tr><tr><td>Default Value Method</td><td>How do you represent the default value of a variable?</td><td>Create a method that returns the value. Prepend "default" to the name of the variable as the name of the method.</td></tr><tr><td>Constant Method</td><td>How do you code a constant?</td><td>Create a method that returns the constant.</td></tr><tr><td>Direct Variable Access</td><td>How do you get and set an instance variable's value?</td><td>Access and set the variable directly.</td></tr><tr><td>Indirect Variable Access</td><td>How do you get and set an instance variable's value?</td><td>Access and set its value only through a Getting Method and Setting Method.</td></tr><tr><td>Getting Method</td><td>How do you provide access to an instance variable?</td><td>Provide a method that returns the value of the variable. Give it the same name as the variable.</td></tr><tr><td>Setting Method</td><td>How do you change the value of an instance variable?</td><td>Provide a method with the same name as the variable. Have it take a single parameter, the value to be set.</td></tr></table>
<table><tr><td>Collection Accessor Method</td><td>How do you provide access to an instance variable that holds a collection?</td><td>Provide methods that are implemented with Delegation to the collection. To name the methods, add the name of the collection to the collection messages.</td></tr><tr><td>Enumeration Method</td><td>How do you provide safe, general access to collection elements?</td><td>Implement a method that executes a Block for each element of the collection. Name the method by concatenating the name of the collection and “Do:.”</td></tr><tr><td>Boolean Property Setting Method</td><td>How do you set a boolean property?</td><td>Create two methods beginning with “be.” One has property name, the other the negation. Add “ toggle” if the client doesn’t want to know about the current state.</td></tr><tr><td>Role Suggesting Instance Variable Name</td><td>What do you name an instance variable?</td><td>Name instance variables for the role they play in the computation. Make the name plural if the variable will hold a Collection.</td></tr><tr><td>Temporary Variable</td><td>How do you save the value of an expression for later use within a method?</td><td>Create a variable whose scope and extent is a single method. Declare it just below the method selector. Assign it as soon as the expression is valid.</td></tr><tr><td>Collecting Temporary Variable</td><td>How do you gradually collect values to be used later in a method?</td><td>When you need to collect or merge objects over a complex enumeration, use a temporary variable to hold the collection or merged value.</td></tr><tr><td>Caching Temporary Variable</td><td>How do you improve the performance of a method?</td><td>Set a temporary variable to the value of the expression as soon as it is valid. Use the variable instead of the expression in the remainder of the method.</td></tr></table>
<table><tr><td>Explaining Temporary Variable</td><td>How do you simplify a complex expression within a method?</td><td>Take a subexpression out of the complex expression. Assign its value to a temporary variable before the complex expression. Use the variable instead in the complex expression.</td></tr><tr><td>Reusing Temporary Variable</td><td>How do you use an expression several places in a method when its value may change?</td><td>Execute the expression once and set a temporary variable. Use the variable instead of the expression in the remainder of the method.</td></tr><tr><td>Role Suggesting Temporary Variable Name</td><td>What do you call a temporary variable?</td><td>Name a temporary variable for the role it plays in the computation.</td></tr><tr><td>Collection</td><td>How do you represent a one-to-many relationship?</td><td>Use a Collection.</td></tr><tr><td>Ordered Collection</td><td>How do you code Collections whose size can't be determined when they are created?</td><td>Use an Ordered Collection as your default dynamically sized Collection.</td></tr><tr><td>Run Array</td><td>How do you compactly code an Ordered Collection or Array where you have the same element many times in a row?</td><td>Use a Run Array to compress long runs of the same element.</td></tr><tr><td>Set</td><td>How do you code a Collection whose elements are unique?</td><td>Use a Set.</td></tr><tr><td>Equality Method</td><td>How do you code equality for new objects?</td><td>If you will be putting objects in a Set, using them as Dictionary keys, or otherwise using them with other objects that define equality, define a method called "=". Protect the implementation of "=" so only objects of compatible classes will be fully tested for equality.</td></tr><tr><td>Hashing Method</td><td>How do you ensure that new objects work correctly with hashed Collections?</td><td>If you override "=" and use the object with a hashed Collection, override "hash"</td></tr></table>
<table>
  <tr>
    <td>Dictionary</td>
    <td>How do you map one kind of object to another?</td>
    <td>Use a Dictionary.</td>
  </tr>
  <tr>
    <td>Sorted Collection</td>
    <td>How do you sort a collection?</td>
    <td>Use a Sorted Collection. Set its sort block if you want to sort by some criteria other than &lt;=.</td>
  </tr>
  <tr>
    <td>Array</td>
    <td>How do you code a collection with a fixed number of elements? "new:anInteger" so that it</td>
    <td>Use an Array. Create it with has space for the number of elements you know it needs.</td>
  </tr>
  <tr>
    <td>Byte Array</td>
    <td>How do you code an Array of numbers in the range 0..255 or -128..127?</td>
    <td>Use a Byte Array.</td>
  </tr>
  <tr>
    <td>Interval</td>
    <td>How do you code a collection of numbers in sequence?</td>
    <td>Use an Interval with start, stop, and an optional step value. The Shortcut Constructor Methods Number&gt;&gt;to: and to:by: build Intervals for you.</td>
  </tr>
  <tr>
    <td>Is Empty</td>
    <td>How do you test if a collection is empty?</td>
    <td>Send is Empty to test whether a collection is empty (has no elements). Use not Empty to test whether a collection has elements.</td>
  </tr>
  <tr>
    <td>Includes:</td>
    <td>How do you search for a particular element in a collection?</td>
    <td>Send includes: and pass the object to be searched for.</td>
  </tr>
  <tr>
    <td>Concatentation</td>
    <td>How do you put two collections together?</td>
    <td>Concatenate two collections by sending "," to the first with the second as an argument.</td>
  </tr>
  <tr>
    <td>Enumeration</td>
    <td>How do you execute code across a collection?</td>
    <td>Use the enumeration messages to spread a com-</td>
  </tr>
</table>
<table><tr><td>Do</td><td>How do you execute code for each element in a collection?</td><td>Send do: to a collection to iterate over its elements. Send a one argument block as the argument to do:. It will be evaluated once for each element.</td></tr><tr><td>Collect</td><td>How do you operate on the result of a message sent to each object in the collection?</td><td>Use collect: to create a new collection whose elements are the results of evaluating the block passed to collect: with each element of the original collection. Use the new collection.</td></tr><tr><td>Select/Reject</td><td>How do you filter out part of a collection?</td><td>Use select: and reject: to return new collections containing only elements of interest. Enumerate the new collection. Both take a one argument Block that returns a Boolean. Select: gives you elements for which the Block returns true, reject: gives you elements for which the Block returns false.</td></tr><tr><td>Detect</td><td>How do you search a collection?</td><td>Search a collection by sending it detect:. The first element for which the block argument evaluates to true will be returned.</td></tr><tr><td>Inject:into:</td><td>How do you keep a running value as you iterate over a Collection?</td><td>Use inject:into: to keep a running value. Make the first argument the initial value. Make the second argument a two-element block. Call the block arguments "sum" and "each." Have the block evaluate to the next value of the</td></tr></table>
<table><tr><td>Duplicate Removing Set</td><td>How do you remove the duplicates from a Collection?</td><td>Send "asSet" to the Collection. The result will have all duplicates removed.</td></tr><tr><td>Temporarily Sorted Collection</td><td>How do you present a Collection with one of many sort orders?</td><td>Return a sorted copy of the Collection by sending "asSortedCollection" to the Collection. Send "asSortedCollection: aBlock" for custom sort orders.</td></tr><tr><td>Stack</td><td>How do you implement a stack?</td><td>Implement a Stack using an Ordered Collection.</td></tr><tr><td>Queue</td><td>How do you implement a queue?</td><td>Implement queues using an Ordered Collection.</td></tr><tr><td>Searching Literal</td><td>How do you search for one of a few literal objects known when you write the code?</td><td>Ask a literal Collection if it includes the element you are seeking.</td></tr><tr><td>Lookup Cache</td><td>How do you optimize complex Detect or Select/Reject loops?</td><td>Prepend "lookup" to the name of the expensive search or filter method. Add an instance variable holding a Dictionary to cache results. Name the variable by appending "Cache" to the name of the search. Make the parameters of the search the keys of the Dictionary and the results of the search the values.</td></tr><tr><td>Parsing Stream</td><td>How do you write a simple parser?</td><td>Put the Stream in an instance variable. Have all parsing methods work from the same Stream.</td></tr><tr><td>Concatenating Stream</td><td>How do you concatenate several Collections?</td><td>Use a Stream to concatenate many Collections.</td></tr><tr><td>Simple Superclass Name</td><td>What do you call a class that is expected to be the root of an</td><td>Name a superclass with a single word that conveys its</td></tr></table>
<table><tr><td>Qualified Subclass Name</td><td>What do you name a new subclass?</td><td>Name subclasses in your hierarchies by prepending an adjective to the superclass name.</td></tr><tr><td>Inline Message Pattern</td><td>How do you format the message pattern?</td><td>Write the message pattern without explicit line breaks.</td></tr><tr><td>Type Suggesting Parameter Name</td><td>What do you call a method parameter?</td><td>Name parameters according to their most general expected class, preceded by "a" or "an." If there is more than one parameter with the same expected class, precede the class with a descriptive word.</td></tr><tr><td>Indexed Control Flow</td><td>How do you indent messages?</td><td>Put zero or one argument messages on the same lines as their receiver. For messages with two or more keywords put each key word/argument pair on its own line, indented one tab.</td></tr><tr><td>Rectangular Block</td><td>How do you format blocks?</td><td>Make blocks rectangular. Use the square brackets as the upper left and bottom right corners of the rectangle. If the statement in the block is simple, the block can fit on one line. If the statement is compound, bring the block onto its own line and indent.</td></tr><tr><td>Guard Clause</td><td>How do you format code that shouldn't execute if a condition holds?</td><td>Format the one-branch conditional with an explicit return.</td></tr><tr><td>Conditional Expression</td><td>How do you format conditional expressions where both branches assign or return a value?</td><td>Format conditionals so their value is used where it clearly expresses the intent of the method.</td></tr></table>
<table><tr><td>Simple Enumeration Parameter</td><td>What do you call the parameter to an enumeration block?</td><td>Call the parameter “each.” If you have nested enumeration blocks, append a descriptive word to all parameter names.</td></tr><tr><td>Cascade</td><td>How do you format multiple messages to the same receiver?</td><td>Use a Cascade to send several messages to the same receiver. Separate the messages with a semicolon. Put each message on its own line and indent one tab. Only use Cascades for messages with zero or one argument.</td></tr><tr><td>Yourself</td><td>How can you use the value of a Cascade if the last message doesn't return the receiver of the message?</td><td>When you need the value of a Cascade and the last message does not return the receiver, append the message “yourself” to the Cascade.</td></tr><tr><td>Interesting Return Value</td><td>When do you explicitly return a value at the end of a method?</td><td>Return a value only when you intend for the sender to use the value.</td></tr></table>
*This page intentionally left blank*
# Index

* #addFloat: Mediating Protocol 58

* #addInteger: Mediating Protocol 58

* Array pattern 133–135

* example 191–201

* arrays

* duplicate elements 118–119

* numbers in a range 135–137

* numbers in sequence 137–138

* become method 8

* behavior, definition 19

* best practice, defined 1

* blocks, formatting 177–178

* Boolean Property Setting Method pattern 100–101

* ByteArray pattern 135–137

* Caching Temporary Variable pattern 106–108

* Cascade pattern 183–185

* last message doesn't return receiver 186–188
Choosing Message pattern 45–47

Choosing Method pattern, example
191–201

classes

Array pattern 133–135

arrays

duplicate elements 118–119

numbers in a range 135–137

numbers in sequence 137–138

ByteArray pattern 135–137

Collection pattern 115–116

collections

duplicate elements 118–119

fixed number of elements 133–135

sorting 131–132

undetermined size, coding 116–117

unique elements 119–124

Dictionary pattern 128–131

Equality Method pattern 124–126

Hashing Method pattern 126–128

Interval pattern 137–138

objects

coding equality 124–126

mapping one to another 128–131

working with hashed collections

126–128

one-to-many relationships 115–116

OrderedCollection pattern 116–117

Qualified Subclass Name pattern

169–170

RunArray pattern 118–119

Set pattern 119–124

Simple Superclass Name pattern

168–169

SortedCollection pattern 131–132

subclasses, naming 169–170

superclasses, naming 168–169

Collect pattern 147–149

Collecting Parameter pattern 75–77

Collecting Temporary Variable pattern

105–106

Collection Accessor Method pattern
96–99

collection idioms

collections

concatenating 165–166

removing duplicates 154–155

sorting temporarily 155–156

Concatenating Stream pattern

165–166

Detect loops, optimizing 161–163

Duplicate Removing Set pattern

154–155

literals, searching for 159–161

Lookup Cache pattern 161–163

parser, writing 164–165

Parsing Stream pattern 164–165

Queue pattern 158–159

queues 158–159

Searching Literal pattern 159–161

Select/Reject loops, optimizing

161–163

Stack pattern 156–158

stacks 156–158

Temporarily Sorted Collection pattern

155–156

Collection pattern 115–116

collection protocols

Collect pattern 147–149

collections

concatenating 143–144

executing code across 144–145

executing code for each element

146–147

filtering 149–150

keeping running values 152–154

results of a message sent to each

object 147–149

searching 151–152

searching for elements 141–143

testing for empty 139–141

Concatenation pattern 143–144
<table>
  <tbody>
    <tr>
      <td>Detect pattern 151-152</td>
    </tr>
    <tr>
      <td>Do pattern 146-147</td>
    </tr>
    <tr>
      <td>Enumeration pattern 144-145</td>
    </tr>
    <tr>
      <td>Includes pattern 141-143</td>
    </tr>
    <tr>
      <td>Inject:into: pattern 152-154</td>
    </tr>
    <tr>
      <td>IsEmpty pattern 139-141</td>
    </tr>
    <tr>
      <td>Select/Reject pattern 149-150</td>
    </tr>
    <tr>
      <td>collections</td>
    </tr>
    <tr>
      <td>concatenating 143-144, 165-166</td>
    </tr>
    <tr>
      <td>duplicate elements 118-119</td>
    </tr>
    <tr>
      <td>executing code across 144-145</td>
    </tr>
    <tr>
      <td>executing code for each element 146-147</td>
    </tr>
    <tr>
      <td>filtering 149-150</td>
    </tr>
    <tr>
      <td>fixed number of elements 133-135</td>
    </tr>
    <tr>
      <td>general access to 99-100</td>
    </tr>
    <tr>
      <td>keeping running values 152-154</td>
    </tr>
    <tr>
      <td>removing duplicates 154-155</td>
    </tr>
    <tr>
      <td>results of a message sent to each object 147-149</td>
    </tr>
    <tr>
      <td>searching 141-143, 151-152</td>
    </tr>
    <tr>
      <td>sorting 131-132</td>
    </tr>
    <tr>
      <td>temporarily 155-156</td>
    </tr>
    <tr>
      <td>testing for empty 139-141</td>
    </tr>
    <tr>
      <td>undetermined size, coding 116-117</td>
    </tr>
    <tr>
      <td>unique elements 119-124</td>
    </tr>
    <tr>
      <td>See also classes</td>
    </tr>
    <tr>
      <td>See also collection idioms</td>
    </tr>
    <tr>
      <td>See also collection protocol</td>
    </tr>
    <tr>
      <td>Common State pattern 80-81</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Comparing Method pattern 32-33</td>
    </tr>
    <tr>
      <td>Composed Method pattern 21-22</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Concatenating Stream pattern 165-166</td>
    </tr>
    <tr>
      <td>Concatenation pattern 143-144</td>
    </tr>
    <tr>
      <td>conditional code, formatting 178-179</td>
    </tr>
    <tr>
      <td>Conditional Expression pattern 180-182</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
  </tbody>
</table>

<table>
  <tbody>
    <tr>
      <td>conditional logic 45-47</td>
    </tr>
    <tr>
      <td>Constant Method pattern 87-89</td>
    </tr>
    <tr>
      <td>constants, coding 87-89</td>
    </tr>
    <tr>
      <td>Constructor Method pattern 23-24</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Constructor Parameter Method pattern 25-26</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Conversion pattern 28</td>
    </tr>
    <tr>
      <td>Converter Constructor Method pattern 29-30</td>
    </tr>
    <tr>
      <td>Converter Method pattern 28-29</td>
    </tr>
    <tr>
      <td>Debug Print Method pattern 39-40</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Decomposing Message pattern 47-48</td>
    </tr>
    <tr>
      <td>Decomposing Method pattern 191-201</td>
    </tr>
    <tr>
      <td>Default Value Method pattern 86-87</td>
    </tr>
    <tr>
      <td>Delegation pattern 64-65</td>
    </tr>
    <tr>
      <td>Detect loops, optimizing pattern 161-163</td>
    </tr>
    <tr>
      <td>Detect pattern 151-152</td>
    </tr>
    <tr>
      <td>Dictionary pattern 128-131</td>
    </tr>
    <tr>
      <td>Direct Variable Access pattern 89-91</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Dispatched Interpretation pattern 51-55</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Do pattern 146-147</td>
    </tr>
    <tr>
      <td>Double Dispatch pattern 55-57</td>
    </tr>
    <tr>
      <td>example 191-201</td>
    </tr>
    <tr>
      <td>Duplicate Removing Set pattern 154-155</td>
    </tr>
    <tr>
      <td>enumeration blocks, naming parameters 182-183</td>
    </tr>
  </tbody>
</table>
Enumeration Method pattern 99–100

Enumeration pattern 144–145

Equality Method pattern 124–126

Execute Around Method pattern 37–39

Explaining Temporary Variable pattern
108–109

Explicit Initialization pattern 83–85

expressions

formatting conditional 180–182

reusing 109–110

saving results of 103–106

simplifying 108–109

Extending Super pattern 60–62

formatting 171–172

blocks 177–178

Cascade pattern 183–188

conditional code 178–179

Conditional Expression pattern

180–182

conditional expressions 180–182

enumeration blocks, naming parame-
ters 182–183

Guard Clause pattern 178–179

Indented Flow Control pattern
175–177

Inline Message Pattern pattern

172–174

Interesting Return Value pattern

188–189

message patterns 172–174

messages

indenting 175–177

multiple to same receiver 183–185

methods

parameters, naming 174–175

returning values from 188–189

Rectangular Block pattern 177–178

Simple Enumeration Parameter pat-
tern 182–183

Type Suggesting Parameter Name

pattern 174–175

Yourself pattern 186–188

Getting Method pattern 93–95

example 191–201

Guard Clause pattern 178–179

Hashing Method pattern 126–128

Includes pattern 141–143

Indexed Control Flow pattern 175–177

example 191–201

Indirect Variable Access pattern 91–93

Inject:into: pattern 152–154

Inline Message Pattern pattern 172–174

example 191–201

instance variables

accessing 93–99

Boolean Property Setting Method pat-
tern 100–101

changing values 95–96

Collection Accessor Method pattern

96–99

collections, general access to 99–100

Common State pattern 80–81

Constant Method pattern 87–89

constants, coding 87–89

Default Value Method pattern 86–87

Direct Variable Access pattern 89–91

Enumeration Method pattern 99–100

Explicit Initialization pattern 83–85

Getting Method pattern 93–95

getting/setting 89–93

Indirect Variable Access pattern

91–93

initializing defaults 83–86

initializing values 86–87

naming 102–103

instances

common states 80–81

creating 23–24

passing parameters to 25–26
<table>
  <tbody>
    <tr>
      <td>variable states</td>
      <td>82–83</td>
    </tr>
    <tr>
      <td>Intention Revealing Messages pattern</td>
      <td>48–49</td>
    </tr>
    <tr>
      <td>Intention Revealing Selector pattern</td>
      <td>49–51</td>
    </tr>
    <tr>
      <td>example</td>
      <td>191–201</td>
    </tr>
    <tr>
      <td>Interesting Return Value pattern</td>
      <td>188–189</td>
    </tr>
    <tr>
      <td>example</td>
      <td>191–201</td>
    </tr>
    <tr>
      <td>Interval pattern</td>
      <td>137–138</td>
    </tr>
    <tr>
      <td>IsEmpty pattern</td>
      <td>139–141</td>
    </tr>
    <tr>
      <td>Lazy Initialization pattern</td>
      <td>85–86</td>
    </tr>
    <tr>
      <td>literals, searching for</td>
      <td>159–161</td>
    </tr>
    <tr>
      <td>Lookup Cache pattern</td>
      <td>161–163</td>
    </tr>
    <tr>
      <td>Mediating Protocol pattern</td>
      <td>57–59</td>
    </tr>
    <tr>
      <td>Message pattern</td>
      <td>43–44</td>
    </tr>
    <tr>
      <td>message patterns, formatting</td>
      <td>172–174</td>
    </tr>
    <tr>
      <td>messages</td>
      <td></td>
    </tr>
    <tr>
      <td>Choosing Message pattern</td>
      <td>45–47</td>
    </tr>
    <tr>
      <td>Collecting Parameter pattern</td>
      <td>75–77</td>
    </tr>
    <tr>
      <td>conditional logic</td>
      <td>45–47</td>
    </tr>
    <tr>
      <td>Decomposing Message pattern</td>
      <td>47–48</td>
    </tr>
    <tr>
      <td>Delegation pattern</td>
      <td>64–65</td>
    </tr>
    <tr>
      <td>Dispatched Interpretation pattern</td>
      <td>51–55</td>
    </tr>
    <tr>
      <td>Double Dispatch pattern</td>
      <td>55–57</td>
    </tr>
    <tr>
      <td>Extending Super pattern</td>
      <td>60–62</td>
    </tr>
    <tr>
      <td>flow control</td>
      <td>33–34</td>
    </tr>
    <tr>
      <td>formatting multiple to same receiver</td>
      <td>183–185</td>
    </tr>
    <tr>
      <td>indenting</td>
      <td>175–177</td>
    </tr>
    <tr>
      <td>Intention Revealing Messages pattern</td>
      <td>48–49</td>
    </tr>
    <tr>
      <td>Intention Revealing Selector pattern</td>
      <td>49–51</td>
    </tr>
    <tr>
      <td>invoking in tandem</td>
      <td>37–39</td>
    </tr>
    <tr>
      <td>Mediating Protocol pattern</td>
      <td>57–59</td>
    </tr>
    <tr>
      <td>Message pattern</td>
      <td>43–44</td>
    </tr>
  </tbody>
</table>

<table>
  <tbody>
    <tr>
      <td>method dispatch</td>
      <td>55–57</td>
    </tr>
    <tr>
      <td>methods</td>
      <td></td>
    </tr>
    <tr>
      <td>breaking into parts</td>
      <td>47–48</td>
    </tr>
    <tr>
      <td>collections resulting from multiple</td>
      <td>75–77</td>
    </tr>
    <tr>
      <td>communicating intent</td>
      <td>48–49</td>
    </tr>
    <tr>
      <td>complex Pluggable Behavior</td>
      <td>73–75</td>
    </tr>
    <tr>
      <td>instance-specific behavior</td>
      <td>70–73</td>
    </tr>
    <tr>
      <td>invoking</td>
      <td>43–44</td>
    </tr>
    <tr>
      <td>naming</td>
      <td>49–51</td>
    </tr>
    <tr>
      <td>Modifying Super pattern</td>
      <td>52–64</td>
    </tr>
    <tr>
      <td>objects</td>
      <td></td>
    </tr>
    <tr>
      <td>cooperating</td>
      <td>51–55</td>
    </tr>
    <tr>
      <td>delegate access</td>
      <td>67–68</td>
    </tr>
    <tr>
      <td>interaction</td>
      <td>57–59</td>
    </tr>
    <tr>
      <td>invoking disinterested delegates</td>
      <td>65–66</td>
    </tr>
    <tr>
      <td>parameterizing behavior</td>
      <td>69–70</td>
    </tr>
    <tr>
      <td>sharing implementation without</td>
      <td>inheritance</td>
    </tr>
    <tr>
      <td>parameterizing behavior</td>
      <td>69–70</td>
    </tr>
    <tr>
      <td> Pluggable Behavior pattern</td>
      <td>69–70</td>
    </tr>
    <tr>
      <td> Pluggable Block pattern</td>
      <td>73–75</td>
    </tr>
    <tr>
      <td> Pluggable Selector pattern</td>
      <td>70–73</td>
    </tr>
    <tr>
      <td> Self Delegation pattern</td>
      <td>67–68</td>
    </tr>
    <tr>
      <td> Simple Delegation pattern</td>
      <td>65–66</td>
    </tr>
    <tr>
      <td> Super pattern</td>
      <td>59–60</td>
    </tr>
    <tr>
      <td> superclass behavior</td>
      <td></td>
    </tr>
    <tr>
      <td>adding to</td>
      <td>60–62</td>
    </tr>
    <tr>
      <td>invoking</td>
      <td>59–60</td>
    </tr>
    <tr>
      <td>modifying</td>
      <td>52–64</td>
    </tr>
    <tr>
      <td>Method Comment pattern</td>
      <td>40–43</td>
    </tr>
    <tr>
      <td>method dispatch</td>
      <td>55–57</td>
    </tr>
    <tr>
      <td>Method Object pattern</td>
      <td>34–37</td>
    </tr>
    <tr>
      <td>methods</td>
      <td></td>
    </tr>
    <tr>
      <td>become</td>
      <td>8</td>
    </tr>
    <tr>
      <td>breaking into parts</td>
      <td>47–48</td>
    </tr>
    <tr>
      <td>collections resulting from multiple</td>
      <td>75–77</td>
    </tr>
    <tr>
      <td>commenting</td>
      <td>40–43</td>
    </tr>
    <tr>
      <td>communicating intent</td>
      <td>48–49</td>
    </tr>
    <tr>
      <td>Comparing Method pattern</td>
      <td>32–33</td>
    </tr>
  </tbody>
</table>
complex Pluggable Behavior 73–75

Composed Method pattern 21–22

Constructor Method pattern 23–24

Constructor Parameter Method pattern 25–26

Conversion pattern 28

Converter Constructor Method pattern 29–30

Converter Method pattern 28–29

Debug Printing Method pattern 39–40

definition 20

Execute Around Method pattern 37–39

instances

creating 23–24

passing parameters to 25–26

instance-specific behavior 70–73

invoking 43–44

messages

flow control 33–34

invoking in tandem 37–39

Method Comment pattern 40–43

Method Object pattern 34–37

naming 49–51, 95

objects

converting 28–30

creating, shortcut 26–27

sorting 32–33

testing properties of 30–32

parameters, naming 174–175

performance tuning 106–108

printing, default method 39–40

programs, dividing into methods 21–22

Query Method pattern 30–32

returning values from 188–189

Reversing Method pattern 33–34

setting boolean properties 100–101

Shortcut Constructor Method pattern 26–27

simplifying complexity 34–37

Modifying Super pattern 52–64

naming

enumeration block parameters 182–183

instance variables 102–103

method parameters 174–175

methods 49–51, 95

subclasses 169–170

superclasses 168–169

temporary variables 110–111

objects

coding equality 124–126

converting 28–30

cooperating 51–55

copying 8

creating, shortcut 26–27

delegate access 67–68

interaction 57–59

invoking disinterested delegates 65–66

mapping one to another 128–131

parameterizing behavior 69–70

sharing implementation without

inheritance 64–65

sorting 32–33

testing properties of 30–32

working with hashed collections 126–128

one-to-many relationships 115–116

OrderedCollection pattern 116–117

parser, writing 164–165

Parsing Stream pattern 164–165

patterns

adopting 9–10

definition 1

examples 191–202

learning 10–11

reasons for 14–15

roles of 15–16

*See also* classes
See also collection idioms
See also collection protocols
See also formatting
See also instance variables
See also messages
See also methods
See also specific pattern names
See also temporary variables
performance tuning 8, 21
Pluggable Behavior pattern 69–70
Pluggable Block pattern 73–75
Pluggable Selector pattern 70–73
printing, default method 39–40
procedure calls {\i vs.} messages and methods 19–20
programming style 6–7
programs
become method 8
coding activities 1–3
copying objects 8
dividing into methods 21–22
exception handling 7–8
flow of control 21
lifecycle cost 5–6
performance tuning 8, 21
productivity 5
quality criteria 4–6
readability 21–22
risk 6
system structure 3–4
time to market 6
Qualified Subclass Name pattern
169–170
Query Method pattern 30–32
Queue pattern 158–159
queues 158–159
Rectangular Block pattern 177–178
example 191–201

Reusing Temporary Variable pattern
109–110
Reversing Method pattern 33–34
Role pattern, example 191–201
Role Suggesting Instance Variable Name pattern 102–103
Role Suggesting Temporary Variable Name pattern 110–111
RunArray pattern 118–119
Searching Literal pattern 159–161
Select/Reject loops, optimizing 161–163
Select/Reject pattern 149–150
Self Delegation pattern 67–68
Set pattern 119–124
Setting Method pattern 95–96
Shortcut Constructor Method pattern
26–27
Simple Delegation pattern 65–66
Simple Enumeration Parameter pattern
182–183
example 191–201
Simple Superclass Name pattern
168–169
example 191–201
SortedCollection pattern 131–132
Stack pattern 156–158
stacks 156–158
state
definition 19
See also instance variables
See also temporary variables
subclasses, naming 169–170
Suggesting Instance Variable Name pattern, example 191–201
Super pattern 59–60
superclass behavior

adding to 60–62

invoking 59–60

modifying 52–64

superclasses, naming 168–169

Temporarily Sorted Collection pattern

155–156

Temporary Variable pattern 103–104

temporary variables

Caching Temporary Variable pattern

106–108

Collecting Temporary Variable pattern

105–106

Explaining Temporary Variable pat-

tern 108–109

expressions

reusing 109–110

saving results of 103–106

simplifying 108–109

methods, performance tuning

106–108

naming 110–111

Reusing Temporary Variable pattern

109–110

Role Suggesting Temporary Variable

Name pattern 110–111

Temporary Variable pattern 103–104

temporary variables, naming 110–111

Type Suggesting Parameter Name pat-

tern 174–175

example 191–201

\#value: Mediating Protocol 58

\#value Mediating Protocol 58

Variable State 82–83

Variable State pattern 82–83

variables, coding 87–89

Yourself pattern 186–188