Object-oriented programming

Course links

Objects: records that protect their fields

When defining a record type in the manner described in the reading on records, the programmer may decide not to define a mutator procedure for some fields (the size field of a record of type shirt, for instance, or the title field of a catalog card). This decision expresses the programmer's judgement that such fields, once initialized, should never be changed.

However, if many programmers are working together on a large programming project, there is no way for the author of a library that contains such a record type to enforce her decision. Records are vectors, and the predefined vector-set! procedure can always be used to change the contents of any position in a vector. The procedures provided by the author of the record package are suggestions, not requirements; a collaborator can always go behind those procedures to operate directly on the vector that implements the record.

One of the basic ideas of the programming paradigm called object-oriented programming is to intercept such low-level interventions and treat them as errors. An object is a data structure that permits access to and modification of its elements only through a fixed set of procedures -- the object's methods. To request the execution of one of these methods, one sends the object a message that names the desired method, providing any additional arguments that the object will need as part of the message. Attempting to send an object a message that does not name one of its methods simply causes an error.

Objects in Scheme

In Scheme, an object is implemented as a procedure that takes messages as parameters and inspects them before acting on them. Static variables, as described in the reading on assignment, denote the record fields that are protected by the procedure.

Here's a simple example -- an object named sample-box that contains only one field, contents, and responds to only one message, :show-contents.

;;; sample-box: a box with constant contents, capable of reporting its
;;; contents on command

;; Given:
;;   MESSAGE, a symbol

;; Result:
;;   CONTENTS, a value

;; Precondition:
;;   MESSAGE is the symbol :SHOW-CONTENTS.

;; Postcondition:
;;   CONTENTS is the value stored in SAMPLE-BOX's static variable.

(define sample-box
  (let ((contents 42))
    (lambda (message)
      (if (eq? message ':show-contents)
          contents
          (error "sample-box: unrecognized message")))))
> (sample-box ':show-contents)
42
> (sample-box ':set-contents-to-zero!)
(bug) sample-box: unrecognized message
> (set! contents 0)
(bug) set!: cannot set undefined identifier: contents
> (sample-box ':show-contents)
42

Both attempts to modify the contents field of sample-box fail. Sending it the message :set-contents-to-zero! doesn't work, because the procedure is not set up to receive such a message. And you can't reach the actual contents variable from outside the sample-box procedure because that identifier is bound to the storage location that contains 42 only inside the body of the let-expression.

One could revise the procedure so that it would accept the message :set-contents-to-zero!:

;;; zeroable-box: a box that can report its contents on demand or replace
;;; them with 0

;; Given:
;;   MESSAGE, a symbol

;; Result:
;;   Either CONTENTS, a value, or no result.

;; Precondition:
;;   MESSAGE is either the symbol :SHOW-CONTENTS or the symbol
;;   :SET-CONTENTS-TO-ZERO!. 

;; Postconditions:
;;   (1) If MESSAGE is :SHOW-CONTENTS, then CONTENTS is the value stored in
;;       ZEROABLE-BOX's static variable.
;;   (2) If MESSAGE is :SET-CONTENTS-TO-ZERO!, then the value stored in
;;       ZEROABLE-BOX's static variable is 0.

(define zeroable-box
  (let ((contents 57))
    (lambda (message)
      (cond ((eq? message ':show-contents) contents)
            ((eq? message ':set-contents-to-zero!) (set! contents 0))
            (else (error "zeroable-box: unrecognized message"))))))
> (zeroable-box ':show-contents)
57
> (zeroable-box ':set-contents-to-zero!)
> (zeroable-box ':show-contents)
0

Of course, there is no way for anyone to set the contents of this particular object to anything except zero, so now that the box has been zeroed its contents will remain zero forever.

Making several objects of the same type

In the preceding examples, we have created only one object of each type, but it is not difficult to write a higher-order constructor procedure that can be called repeatedly, to build and return any number of objects of a given type. Suppose, for example, that we want to build several switches, each of which is an object with one field (a Boolean value) and responding to only two messages: :show-position, which returns the symbol on if the field contains #t and off if it contains #f, and :toggle!, which changes the field from #t to #f or from #f to #t. Here's a constructor for switches:

;;; make-switch: construct and return an object that remembers whether it
;;; is on or off and can reveal or change its state on command

;; Givens:
;;   None

;; Result:
;;   SWITCH, a unary procedure

;; Preconditions:
;;   None.

;; Postconditions:
;;   (1) SWITCH is initially off.
;;   (2) When SWITCH is invoked with the argument :SHOW-POSITION, it
;;       returns the symbol OFF if it is off and the symbol ON if it is
;;       on.
;;   (3) When SWITCH has been invoked with the argument :TOGGLE!, it is on
;;       if it was formerly off and off if it was formerly on.
;;   (4) It is an error to give SWITCH any other argument when invoking it.

(define make-switch
  (lambda ()
    (let ((state #f))
      (lambda (message)
        (cond ((eq? message ':show-position) (if state 'on 'off))
              ((eq? message ':toggle!) (set! state (not state)))
              (else (error "switch: unrecognized message")))))))

Now let's manufacture a couple of switches and show that they can be toggled independently:

> (define lamp-switch (make-switch))
> (define vacuum-cleaner-switch (make-switch))
> (lamp-switch ':show-position)
off
> (vacuum-cleaner-switch ':show-position)
off
> (lamp-switch ':toggle!)
> (lamp-switch ':show-position)
on
> (vacuum-cleaner-switch ':show-position)
off
> (lamp-switch ':toggle!)
> (vacuum-cleaner-switch ':toggle!)
> (lamp-switch ':show-position)
off
> (vacuum-cleaner-switch ':show-position)
on

Because the make-switch procedure enters the let-expression to create a new binding each time it is invoked, each switch that is returned by make-switch gets a separate static variable to put its state in. This static variable retains its contents unchanged even between calls to the object and independently of calls to any other object of the same type.

Methods with additional arguments

In the preceding examples, the messages received by the object have not included any additional arguments. Suppose that we want to define an object like sample-box except that one can replace the value in the contents field with any integer that is larger than the one that it currently contains, by sending it the message :replace-with! and including the new, larger value. We can accommodate such messages by making the object a procedure of variable arity, requiring at least one argument (the name of the method to be applied) but allowing for more:

;;; growing-box: a box with constant contents, capable of reporting its
;;; contents, or replacing them with larger values, on command

;; Givens:
;;   MESSAGE, a symbol
;;   (optionally) NEW-VALUE, an integer

;; Result:
;;   CONTENTS, a value

;; Preconditions:
;;   (1) MESSAGE is either the symbol :SHOW-CONTENTS or the symbol
;;       :REPLACE-WITH!.
;;   (2) If MESSAGE is :SHOW-CONTENTS, then the NEW-VALUE argument is
;;       not provided.
;;   (3) If MESSAGE is :REPLACE-WITH!, then NEW-VALUE is provided and is
;;       greater than the value stored in GROWING-BOX's static variable.

;; Postcondition:
;;   CONTENTS is the value stored in GROWING-BOX's static variable.

(define growing-box
  (let ((contents 0))
    (lambda (message . arguments)
      (cond ((eq? message ':show-contents)
             (if (null? arguments)
                 contents
                 (error (string-append "growing-box:show-contents: "
                                       "no arguments are required"))))

            ((eq? message ':replace-with!)
             (cond ((null? arguments)
                    (error (string-append "growing-box:replace-with!: "
                                          "an argument is required")))
                   ((not (null? (cdr arguments)))
                    (error (string-append "growing-box:replace-with!: "
                                          "only one argument is required")))
                   (else
                    (let ((new-contents (car arguments)))
                      (cond ((not (integer? new-contents))
                             (error (string-append
                                     "growing-box:replace-with!: "
                                     "the argument must be an integer")))
                            ((<= new-contents contents)
                             (error (string-append
                                     "growing-box:replace-with!: "
                                     "the argument must exceed the current contents")))
                            (else (set! contents new-contents)))))))

            (else (error "growing-box: unrecognized message"))))))
> (growing-box ':show-contents)
0
> (growing-box ':replace-with! 5)
> (growing-box ':show-contents)
5
> (growing-box ':replace-with! 3)
(bug) growing-box:replace-with!: the argument must exceed the current contents
> (growing-box ':show-contents)
5
> (growing-box ':replace-with! 'foo)
(bug) growing-box:replace-with!: the argument must be an integer
> (growing-box ':replace-with!)
(bug) growing-box:replace-with!: an argument is required
> (growing-box ':show-contents)
5
> (growing-box ':replace-with! 7)
> (growing-box ':show-contents)
7

Objects with several fields

To define an object with several fields, some mutable, some not, one places creates several static variables in the let-expression that encloses the object procedure and provides mutation messages for the mutable fields but not for the immutable ones. For instance, here is a constructor for a kind of box that remembers its initial contents in a separate, immutable field and can restore them on demand. Each such box responds to three messages: :show-contents, :change-contents!, and :restore-initial-contents!:

;;; make-restorable-box: construct and return an object that remembers a
;;; value and can reveal or replace its contents, or restore its initial
;;; contents, on command

;; Given:
;;   INITIALIZER, a value

;; Result:
;;   RESTORABLE-BOX, a procedure

;; Preconditions:
;;   None.

;; Postconditions:
;;   (1) Initially, RESTORABLE-BOX contains INITIALIZER.
;;   (2) When RESTORABLE-BOX is invoked with the argument :SHOW-CONTENTS,
;;       it returns its current contents.
;;   (3) When RESTORABLE-BOX has been invoked with :CHANGE-CONTENTS! as its
;;       first argument and some value NEW-CONTENTS as its second, it
;;       contains NEW-CONTENTS.
;;   (4) When RESTORABLE-BOX has been invoked with the argument
;;       :RESTORE-INITIAL-CONTENTS!, it contains INITIALIZER.
;;   (5) It is an error to give RESTORABLE-BOX any other argument when
;;       invoking it, or to give it more than one argument when its first
;;       argument is :SHOW-CONTENTS or :RESTORE-INITIAL-CONTENTS!, or to
;;       give it only one argument, or more than two, when its first
;;       argument is CHANGE-CONTENTS!.

(define make-restorable-box
  (lambda (initializer)
    (let ((contents initializer)
          (initial-contents initializer))
      (lambda (message . arguments)
        (cond ((eq? message ':show-contents)
               (if (null? arguments)
                   contents
                   (error (string-append "restorable-box:show-contents: "
                                         "no arguments are required"))))

              ((eq? message ':change-contents!)
               (cond ((null? arguments)
                      (error (string-append "restorable-box:change-contents!: "
                                            "an argument is required")))
                     ((not (null? (cdr arguments)))
                      (error (string-append "restorable-box:change-contents!: "
                                            "only one argument is required")))
                     (else
                      (set! contents (car arguments)))))

              ((eq? message ':restore-initial-contents!)
               (if (null? arguments)
                   (set! contents initial-contents)
                   (error (string-append "restorable-box:restore-initial-contents!: "
                                         "no arguments are required"))))

              (else
               (error "restorable-box: unrecognized message")))))))
> (define my-box (make-restorable-box 'JDS))
> (my-box ':show-contents)
jds
> (my-box ':change-contents! 'HW)
> (my-box ':show-contents)
hw
> (my-box ':restore-initial-contents!)
> (my-box ':show-contents)
jds

I am indebted to Professor Ben Gum for his contributions to the development of this reading.