Subject: Re: Is this an abuse of CLOS?
From: Erik Naggum <erik@naggum.net>
Date: Sun, 28 Apr 2002 22:22:38 GMT
Newsgroups: comp.lang.lisp
Message-ID: <3229021358194544@naggum.net>

* Peter Seibel
| Suppose I have a bunch of classes that can be used to represent parts of
| a binary file that i'm parsing.

  Been there.  Messy any way you look at it.

| As I parse the file, I read one byte that tells me what the next chunk of
| data is and I instantiate an instance of the appropriate class and call
| the generic function 'read-from' which is specialized on each type to
| read the right amount of data to fill in the object.

  It appears to me that the number of classes involved here is tied to (the
  version of) (the specification of) the binary format and is very unlikely
  to change during program execution in a way that makes a variable with a
  mapping vector meaningful, but if they change at all, and this is very
  likely to happen if my experience of the past is futurable.  (That should
  be a word.)

| So given a function like:
| 
|   (defun read-cp-info (in)
|     "Create an instance of the appropriate subclass of cp-info based on
|   the data read from the current position of the stream 'in'"
|     (let ((cp-info (make-cp-info (read-u1 in))))
|       (read-from cp-info in)
|       cp-info))

  Why not let read-from return the instance?

(read-from (make-cp-info (read-u1 in)) in)

| I can't decide if this latter solution is clever or stupid.  (Or, for all
| I know, it so obvious that it's neither clever nor stupid.)  What do you
| think?

  I think you should make a generic function read-from that specializes on
  the tag and which returns a fully constructed instance, not just an
  instance that you would call another generic function to fill in:

(defgeneric read-cp-info (tag stream))

(defmethod read-cp-info ((tag (eql 7)) (stream stream))
  (let ((... build initargs ...))
    (make-instance 'class-info ... initargs ...)))

  You would then call it with

(read-cp-info (read-u1 in) in)
  
///
-- 
  In a fight against something, the fight has value, victory has none.
  In a fight for something, the fight is a loss, victory merely relief.

  Post with compassion: http://home.chello.no/~xyzzy/kitten.jpg