Pattern: Accessor Methods


Context

The state of an object is defined by the values of its instance variables. An object can access its own instance variables directly, but they are hidden from other objects. The variables that define the public state of the object must be made accessible by adding appropriate methods to manipulate them.

Solution

So called, accessor methods, provide a mechanism for getting and setting the instance variables of an object. For public non-boolean instance variables, there should be two accessor methods:

For public boolean variables, there are generally several accessor methods:

Resist the temptation to call your accessor methods getXxxxxx and setXxxxxx:.

Example

Object subclass: #Car
	instanceVariableNames: 'wheels convertible '
	classVariableNames: ''
	poolDictionaries: ''

wheels
	"Answer the instance variable wheels.
	wheels represents the number of wheels of the receiver."

	^wheels

wheels: anInteger
	"Set the instance variable wheels to anInteger.
	See the get method for a description of wheels."

	wheels := anInteger

isConvertible
"Answer whether the receiver is convertible."

	^convertible

beConvertible
	"Make the receiver be a convertible."

	convertible := true

beNotConvertible
	"Make the receiver be not convertible."

	convertible := false

Consequences

Although an object can access its instance variables directly, it is sometimes a good idea for an object to use private accessor methods to access its own instance variables. This is to increase the opportunity for subclassing in the future, and to reduce the dependency on implementation details. Consider a class that contains a boolean instance variable. If the boolean data was re-implemented as a single 'bit' in a flag bit-pattern, then all direct references to the old boolean variable would have to be visited and changed accordingly. Accessor methods such as this, which are only intended to be used by the receiver, should be marked as private.

Related Patterns