Re: with-slots usage question

Peter Seibel <[email protected]> 10 Nov 2003 10:15:54 -0800
Newsgroups gmane.lisp.clump
Message-ID <[email protected]>
Miles Egan <[email protected]> writes:

> On Mon, 2003-11-10 at 09:12, Peter Seibel wrote:
> > Miles Egan <[email protected]> writes:
> > 
> > > Since discovering with-slots I've started using it pretty heavily in my
> > > code since it really cuts down the verbosity of clos-based code.  It
> > > makes me a little uneasy that with-slots goes directly to the slot value
> > > without using an accessor though.  I suppose the more proper thing would
> > > be to use with-accessors but it seems so much more verbose.
> > > 
> > > The ideal thing would be a with-? macro that's as terse as with-slots
> > > but does invoke accessor functions.  Does such a macro exist?  Would it
> > > be possible to write one without using the MOP?
> > 
> > Assuming you're happy to live with the variable names matching the
> > accessor names, doesn't this do what you want? (Coming up with a
> > better name than with-foo is left as an exercise for the reader):
> > 
> >   (defmacro with-foo ((&rest names) obj &body body)
> >     `(with-accessors ,(mapcar #'(lambda (n) (list n n)) names) ,obj
> >        ,@body))
> 
> I considered doing this, but I usually tend to use accessors like
> class-field (message-subject, message-author, etc in macho, for
> instance). Maybe this is bad form?

There's a school of thought (which I happen to subscribe to) that says
it is bad form. If you name your accesors this way, then when you
write subclasses the names expose what level of the class hierarchy
the accessors were defined in:

  (defclass foo ()
    ((x :accessor foo-x)))

  (defclass bar (foo)
    ((y :accessor bar-y)))

  (let ((b (make-instance 'bar)))
    (setf (foo-x b) 10)  ; ugly, I think
    (setf (bar-y b) 20))

The other point--which is sort of theoretical--is that when you are
defining an accessor you are really defining a generic function (and a
method specialized on this class). And GF's should really be viewed as
existing independently of classes, therefore should be named in
class-neutral ways.

> The biggest problem I have with the above is that even if I can
> assume it will work with my own code I can't guarantee it will work
> with someone else that's used different naming conventions.

Well, the caller of with-foo is required to know, and use the actual
names of the accessors. If you want to be able to use variables with
names different than the accessors, that's what with-accessors is for.

-Peter

-- 
Peter Seibel                                      [email protected]

         Lisp is the red pill. -- John Fraser, comp.lang.lisp