AW: [plt-scheme] Changing field values in objects
On Fri, 2 Feb 2007, Robert Matovinovic wrote:
> The cookbook unfortunately doesn't help with that.
Hi Robert,
Are you sure? I'm pretty sure I had something about this... checking...
ah, ok, I see.
There are some example of methods that indirectly allow people to mutate
objects. For example, the example where people can meet other people:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define person%
(class object%
(init-field name)
(define friends '())
(super-new)
(define/public (add-friend other)
(set! friends (cons other friends)))
(define/public (meet-all)
(for-each
(lambda (f) (printf "hi ~a~%" (get-field name f)))
friends))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
I didn't understand fields as well back when I wrote the guide. But
currently, in my own programming, I try to avoid fields if I can because
they're equivalent to "public" attributes in other programming languages.
I like encapsulation. *grin*
So in a hypothetical revision of the guide, I'm planning not to use fields
at all, so that the example above will look like:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define person%
(class object%
(init name)
(define -name name)
(define friends '())
(define/public (get-name) -name)
(define/public (add-friend other)
(set! friends (cons other friends)))
(define/public (meet-all)
(for-each
(lambda (f) (printf "hi ~a~%" (send f get-name)))
friends)))
(super-new))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
which matches much more closely with how classes in Java are done: private
attributes, public accessors. Plus this example shows a case where one
object is politely sending one message to another object, rather than
impolitely digging into concrete implementation details of that object.
I just have to motivate myself to get this hypothetical revision all
done... Stupid procrastination... *grin*
Best of wishes!