Navigation:  Appendix B: Dolphin Pattern Book > Method Patterns >

Accessor Method

Previous pageReturn to chapter overviewNext page


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.

Also Known As

Getting Method, Setting Method


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:

a 'get' method with the same name as the instance variable
a 'set' method with the same name as the instance variable, but is followed by a ':' (colon)

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

"set" methods of the form #beXXX and #beNotXXX which set the value of the variable
"get" methods of the form #isXXX

Resist the temptation to call your accessor methods #getXXX and #setXXX:.


Object subclass: #Car

  instanceVariableNames: 'wheels convertible '

  classVariableNames: ''

  poolDictionaries: ''



  "Answer the instance variable wheels.

  wheels represents the number of wheels of the receiver."



wheels: anInteger

  "Set the instance variable wheels to anInteger.

  See the get method for a description of wheels."

  wheels := anInteger



"Answer whether the receiver is convertible."




  "Make the receiver be a convertible."

  convertible := true



  "Make the receiver be not convertible."

  convertible := false


Known Uses

The sample VideoTape class has accessor "get" methods, #name and #length.


  "Answer the <readableString> name of the receiver."




  "Answer the <Integer> length in minutes of the receiver."



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

Instance Variable Name