September 23, 2023

A guide to Smalltalk accessor messages


Here are a few guidelines for using accessor messages.

  1. When writing a setter method, you must use assignment to set an instance variable. For example:
    width: aNumber
       "Set the width of the receiver to aNumber (a
       positive number between 1 and 10). Answer the
       (aNumber between: 1 and: 10)
          ifTrue: [width := aNumber]
  2. The M206 'house-style' is to reuse the accessor messages from within other methods of the same class. This requires the use of self rather than making direct access to the instance variable. For example, reuse of the width: setter message in another method of the same class:
       "Increment the width of the receiver by 1. Answer
       the receiver."
       self width: self width + 1

    This ensures that the restriction on width is maintained i.e. inconsistent behaviour is avoided. Whereas the direct access of the width instance variable with:
       "Increment the width of the receiver by 1. Answer
       the receiver."
       width := width + 1
       "The check for width is not reused. This could
       cause width to be incremented to a value greater
       than 10!"
  3. Direct access of instance variables is NOT ALWAYS A BAD THING. There are many occasions where reusing an accessor with self or making direct access of the instance variable matters not a jot. However, and this is a personal view, getting into the habit of reusing an accessor message is NO BAD THING.
    Which brings me to the next contentious issue.
  4. There are plenty of programmers who will say, with good reason, that just because you have an instance variable it is not always necessary to write accessor messages for it. Here is a quote from Kent Beck's book Smalltalk - Best Practice Patterns:

    "I told Ward (Cunningham) of my experience. He had another good explanation. When you write classes that only have a handful of methods, adding a getting and a setting method can easily double the number of methods in your class - twice as many methods to buy flexibility that you may never use. On the other hand, it's awfully frustrating to get a class from someone and see the opportunity to quickly subclass it, only to discover that they used Direct Access, so there is no way to make the changes you want without changing most of the code in the superclass".

  5. The above quote is, I think, of great interest and makes perfect sense. For the purposes of M206 don't put guideline 4 into practice unless you are instructed to do so. In other words, always follow the specification.

The next few pages will illustrate many of the concepts covered in this introduction to objects. Hopefully it will provide a better understanding of the object paradigm.

Next page » Artwork class

Previous page « Accessors
































































Up to top of page