Pattern: Temporary Variables


Context

Sometimes it is necessary and/or convenient to store the value of an expression so that it can be used later within the method.

Solution

Temporary variables are useful in a number of areas:

The syntax for temporary variable names naming convention for temporary variables is the same as that for instance variables. The name should begin with a lowercase letter, and if a compound word is used, then subsequent words should begin with an uppercase letter.

The name should describe the role (not the type) of the temporary variable within the context of the method.

Avoid using a temporary variable for more than one purpose within a method.

Known Uses

Collection>>asArray uses a temporary variable answer to build an Array containing the same elements as the receiver:

asArray
	"Answer an Array whose elements are those of the receiver.
	(ordering is that of the #do: operation as implemented by the receiver)."

	| answer i |
	answer:= Array new: self size.
	i := 1.
	self do: [:e |
		answer at: i put: e.
		i := i + 1].
	^answer