home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Information / Languages / Lisp / lisp-faq⁄part5 < prev    next >
Encoding:
Internet Message Format  |  1994-12-08  |  29.1 KB  |  [TEXT/R*ch]

  1. Path: bloom-beacon.mit.edu!uhog.mit.edu!nntp.club.cc.cmu.edu!cantaloupe.srv.cs.cmu.edu!mkant
  2. From: mkant+@cs.cmu.edu (Mark Kantrowitz)
  3. Newsgroups: comp.lang.lisp,comp.lang.clos,news.answers,comp.answers
  4. Subject: FAQ: Object-oriented Programming in Lisp 5/7 [Monthly posting]
  5. Supersedes: <LISP_5_782031621@CS.CMU.EDU>
  6. Followup-To: poster
  7. Date: 13 Nov 1994 08:01:49 GMT
  8. Organization: Carnegie-Mellon University, School of Computer Science
  9. Lines: 600
  10. Approved: news-answers-request@MIT.Edu
  11. Distribution: world
  12. Expires: 25 Dec 1994 08:00:25 GMT
  13. Message-ID: <LISP_5_784713625@CS.CMU.EDU>
  14. References: <LISP_4_784713625@CS.CMU.EDU>
  15. Reply-To: ai+lisp-faq@cs.cmu.edu
  16. NNTP-Posting-Host: glinda.oz.cs.cmu.edu
  17. Summary: Questions about CLOS, PCL and object-oriented programming in Lisp
  18. Xref: bloom-beacon.mit.edu comp.lang.lisp:7455 comp.lang.clos:1246 news.answers:29286 comp.answers:8319
  19.  
  20. Archive-name: lisp-faq/part5
  21. Last-Modified: Thu Oct 20 21:47:27 1994 by Mark Kantrowitz
  22. Version: 1.51
  23. Maintainer: Mark Kantrowitz and Barry Margolin <ai+lisp-faq@cs.cmu.edu>
  24. URL: http://www.cs.cmu.edu:8001/Web/Groups/AI/html/faqs/lang/lisp/top.html
  25. Size: 29242 bytes, 608 lines
  26.  
  27. ;;; ****************************************************************
  28. ;;; Answers to Frequently Asked Questions about Lisp ***************
  29. ;;; ****************************************************************
  30. ;;; Written by Mark Kantrowitz and Barry Margolin
  31. ;;; lisp_5.faq
  32.  
  33. This post contains Part 5 of the Lisp FAQ. It is cross-posted to the
  34. newsgroup comp.lang.clos because it contains material of interest to
  35. people concerned with CLOS, PCL and object-oriented programming in
  36. Lisp. The other parts of the Lisp FAQ are posted only to the
  37. newsgroups comp.lang.lisp and news.answers.
  38.  
  39. If you think of questions that are appropriate for this FAQ, or would
  40. like to improve an answer, please send email to us at ai+lisp-faq@cs.cmu.edu.
  41.  
  42. CLOS/PCL Questions (Part 5):
  43.  
  44.   [5-0]   What is CLOS (PCL) and where can I get it?
  45.           How do you pronounce CLOS? What is the Meta-Object Protocol (MOP)?
  46.   [5-1]   What documentation is available about object-oriented
  47.           programming in Lisp?  
  48.   [5-2]   How do I write a function that can access defstruct slots by
  49.           name?  I would like to write something like 
  50.           (STRUCTURE-SLOT <object> '<slot-name>).   
  51.   [5-3]   How can I list all the CLOS instances in a class?
  52.   [5-4]   How can I store data and CLOS instances (with possibly circular
  53.           references) on disk so that they may be retrieved at some later
  54.           time? (Persistent Object Storage)
  55.   [5-5]   Given the name of a class, how can I get the names of its slots?
  56.   [5-6]   Free CLOS software.
  57.   [5-7]   Common CLOS Blunders
  58.  
  59. Search for \[#\] to get to question number # quickly.
  60.  
  61. In general, questions about object oriented programming in Lisp,
  62. especially questions about using CLOS or compiling PCL, should be
  63. directed to the newsgroup comp.lang.clos.
  64.  
  65. ----------------------------------------------------------------
  66. Subject: [5-0]  What is CLOS (PCL) and where can I get it?
  67.                 How do you pronounce CLOS?
  68.  
  69. CLOS (Common Lisp Object System) is the object-oriented programming
  70. standard for Common Lisp. It is the successor to Symbolics FLAVORS and
  71. Xerox LOOPS (Lisp Object Oriented Programming System). The acronym
  72. CLOS is pronouned either as "See-Loss" or "Closs", depending on taste.
  73. PCL (Portable Common Loops) is a portable CLOS implementation, and is
  74. available by anonymous ftp from 
  75.    parcftp.xerox.com:/pub/pcl/ [13.1.64.94]
  76. Also in the same directory are sources for CLX R5 and an inspecter.
  77.  
  78. Most Common Lisp implementations now include their own CLOS
  79. implementations. Common Lisp implementations with native CLOS include:
  80. MCL, {A}KCL, Allegro CL (including Allegro CL\PC), Ibuki, Lucid,
  81. Medley, Symbolics Genera, CLOE, and Harlequin Lispworks. CMU CL uses a
  82. customized version of PCL as their CLOS. However, not all native CLOS
  83. implementations have as detailed a meta-object protocol as PCL. For
  84. example, MCL 2.0 users sometimes use the july-1d version of PCL
  85. instead of the native CLOS for precisely this reason.
  86.  
  87. The book ``The Art of the Metaobject Protocol'' (see below) includes
  88. the CLOS Metaobject Protocol specification as chapters 5 and 6.  The
  89. sources for the MOP spec itself are available from 
  90.    parcftp.xerox.com:/pub/pcl/mop/ [13.1.64.94]
  91. as the file spec.tar.Z, but this is no substitute for buying the
  92. book, since the book contains a lot of useful explanatory material
  93. beyond the spec. The Closette files related to the book are also
  94. available from parcftp as the file closette.lisp.
  95.  
  96. The CLOS code repository is available by anonymous ftp to
  97.    nervous.cis.ohio-state.edu:/pub/lispusers/clos/ [128.146.61.200] 
  98. If you've got code you'd like to add to the repository, send mail to
  99. Arun Welch, commonloops-request@cis.ohio-state.edu. 
  100.  
  101. ----------------------------------------------------------------
  102. Subject: [5-1] What documentation is available about object-oriented
  103.                programming in Lisp? 
  104.  
  105. Books about object-oriented programming in Lisp include:
  106.  
  107.    1. dpANS CL describes the entire Common Lisp language, which includes the
  108.       CLOS standard.  Informally, CLtL2 can also be used to learn about CLOS, 
  109.       but please remember that CLtL2 is not an official X3J13 committee
  110.       document. (The presentation of CLtL2 differs from that of the draft
  111.       proposed standard, and some matters of fact have changed in the proposed
  112.       standard since the publication of CLtL2.)
  113.  
  114.    2. Sonya E. Keene
  115.       "Object-Oriented Programming in Common Lisp: 
  116.        A Programmer's Guide to CLOS"
  117.       Addison-Wesley (Reading, MA), 1989. 266 pages. ISBN 0-201-17589-4.
  118.            Tutorial introduction to CLOS with many examples and
  119.            a lot of good advice for designing large programs using CLOS.
  120.  
  121.    3. Jo A. Lawless and Molly M. Miller.
  122.       "Understanding CLOS: the Common Lisp Object System"
  123.       Digital Press, 1991. 192 pages.
  124.  
  125.    4. Gregor Kiczales, Jim des Rivieres, and Daniel G. Bobrow.
  126.       "The Art of the Metaobject Protocol"
  127.       MIT Press, 1991. 335 pages. ISBN 0-262-61074-4, $34.95.
  128.            The first part of the book presents a model CLOS implementation,
  129.            introduces the basic principles of metaobject protocols, and 
  130.            works through the key elements of the CLOS Metaobject Protocol.
  131.            The second half is the detailed specification of the CLOS
  132.            Metaobject Protocol. A simple working interpreter suitable
  133.            for experimentation is contained in an appendix.
  134.  
  135.    5. Robert R. Kessler and Amy R. Petajan.
  136.       "LISP, Objects, and Symbolic Programming"
  137.       Scott, Foresman and Company (Glenview, IL), 1988. 644 pages.
  138.            Includes a small Lisp compiler.
  139.  
  140.    6. A short introduction to CLOS written by Jeff Dalton of the
  141.       University of Edinburgh <J.Dalton@ed.ac.uk> is available by
  142.       anonymous ftp from  
  143.          aiai.ed.ac.uk:/lisp/random [192.41.104.6]
  144.       as the file clos-guide.
  145.  
  146.    7. Andreas Paepcke, editor.
  147.       "Object-Oriented Programming: The CLOS Perspective"
  148.       MIT Press, 1993. 400 pages, ISBN 0-262-16136-2 ($40).
  149.          This book is a collection of essays on the following topics:
  150.            -  Description of CLOS and its design philosophy.
  151.            -  The Metaobject Protocol and its use.
  152.            -  Comparison of CLOS with Smalltalk, Eiffel, Sather, and C++.
  153.            -  CLOS Uses and Methodology. Descriptions of two large CLOS
  154.               applications (Sun's LispView and a hybrid knowledge
  155.               representation tool) and an approach to documenting
  156.               object-oriented protocols (similar to that of AMOP).
  157.            -  Implementation details. Descriptions of TI CLOS for the
  158.               Explorer and PCL's method dispatch mechanism.
  159.  
  160. ----------------------------------------------------------------
  161. Subject: [5-2] How can I write a function that can access defstruct slots 
  162.                by name?  I would like to write something like 
  163.                (STRUCTURE-SLOT <object> '<slot-name>).
  164.  
  165. There is currently no portable, built-in way to access structure slots
  166. given only the name.  If your Common Lisp includes an implementation
  167. of CLOS that supports the meta-object protocol specified in the
  168. original X3J13 draft spec (document X3J13/88-003), then it probably will
  169. allow (SLOT-VALUE <object> '<slot-name>); however, not all
  170. implementations of CLOS currently provide this.  Lacking this, some
  171. implementations may provide implementation-dependent functions that
  172. allow access to structure slots by name; note that this may cause
  173. saved images to be larger, as some implementations normally open-code
  174. structure accessors and discard slot name information.
  175.  
  176. While it is not possible to write a fully general STRUCTURE-SLOT function,
  177. it is not very difficult to write version that handles specific structure
  178. types.  For instance, after defining:
  179.  
  180.    (defstruct spaceship name captain position velocity)
  181.  
  182. one may then define:
  183.  
  184.    (defun spaceship-slot (spaceship slot-name)
  185.      (ecase slot-name
  186.        (name (spaceship-name spaceship))
  187.        (captain (spaceship-captain spaceship))
  188.        (position (spaceship-position spaceship))
  189.        (velocity (spaceship-velocity spaceship))))
  190.  
  191. or using CLOS (generic functions):
  192.  
  193. (defgeneric spaceship-slot (spaceship slot-name)
  194.   (:method ((x spaceship) (slot (eql :name)))
  195.     (spaceship-name x))
  196.   (:method ((x spaceship) (slot (eql :captain)))
  197.     (spaceship-captain x))
  198.   (:method ((x spaceship) (slot (eql :position)))
  199.     (spaceship-position x))
  200.   (:method ((x spaceship) (slot (eql :velocity)))
  201.     (spaceship-velocity x)))
  202.  
  203. Another popular way to define this is:
  204.  
  205.    (defun spaceship-slot (spaceship slot-name)
  206.      (funcall (symbol-function
  207.                 (find-symbol (format nil "SPACESHIP-~A" slot-name)
  208.                              #.(package-name *package*)))
  209.               spaceship))
  210.  
  211. I personally recommend the first version.  It is likely to be much faster
  212. and more memory efficient than the second version.  It's also easy to get
  213. the second one wrong; many people forget to specify the package argument to
  214. FIND-SYMBOL, which can cause incorrect results when the package at run time
  215. is different from the one at compile time.  Even my version assumes that
  216. SPACESHIP-SLOT is being defined in a file that is in the same package as
  217. the one containing the structure definition; if this isn't the case,
  218. #.(PACKAGE-NAME *PACKAGE*) should be replaced by a string naming the
  219. correct package.
  220.  
  221. Another workaround is to define a MY-DEFSTRUCT macro that parses the
  222. defstruct arguments and expands into a call to DEFSTRUCT along with a
  223. definition of the runtime slot-accessor function.
  224.  
  225. Some non-portable techniques include the use of SYSTEM:STRUCTURE-REF
  226. in Lucid (LCL:STRUCTURE-REF in earlier versions of Lucid) and 
  227. EXCL:STRUCTURE-REF in Allegro. 
  228. ----------------------------------------------------------------
  229. Subject: [5-3] How can I list all the CLOS instances in a class?
  230.  
  231. There is no built-in way to enumerate the instances of a class.  If you are
  232. only interested in listing the instances of classes that you have defined,
  233. it is not very difficult to implement it as part of your class definition.
  234. Add a shared slot, e.g. ALL-INSTANCES, with an initial value of NIL, to the
  235. class definition.  Then write an after-method on INITIALIZE-INSTANCE for
  236. this class, which pushes the instance being initialized onto ALL-INSTANCES.
  237. Note that this must be done separately for each class that wants to maintain
  238. such a list; it can't be encapsulated in a mixin class, because all its
  239. dependent classes would share the same ALL-INSTANCES slot.  A compromise
  240. would be to use a mixin to define the INITIALIZE-INSTANCE after-method (and
  241. any other general-purpose methods that use the slot), but not the shared
  242. slot; it would be up to the descendant classes to define the slot at the
  243. level of the class hierarchy that is appropriate. You could also try
  244. defining the classes that need instance-recording as instances of a
  245. metaclass that holds the instance registry on the class object. The
  246. recording behavior could then be built-in to an after method on
  247. initialize-instance for the root class of the metaclass, or even
  248. allocate-instance. To allow for garbage collection of old instances,
  249. you will also need to define a generic function to remove the recorded
  250. instances from the list of instances.
  251. ----------------------------------------------------------------
  252. Subject: [5-4]  How can I store data and CLOS instances (with possibly 
  253.                 circular references) on disk so that they may be
  254.                 retrieved at some later time? (Persistent Object Storage)
  255.  
  256. There are two approaches to CLOS object persistence. The first uses
  257. regular CLOS facilities in concert with a standard file system. The
  258. second uses a more sophisticated storage facility, such as a database.
  259. The first solution provides just the persistence, and usually cannot
  260. retrieve only some of the objects from disc. The second goes beyond this
  261. by providing some or all of the facilities typically associated with
  262. databases: transaction management, concurrency control, queries,
  263. selective object materialization, etc. Below, the two solutions are
  264. addressed in turn.
  265.  
  266. There are two main techniques for the file system solution. The first
  267. involves using #. to compile the data into a file.  The second
  268. produces an ASCII representation which, when evaluated, will reproduce
  269. an equivalent set of data.
  270.  
  271. If the data you wish to save is stored in the variable *hash-table*,
  272. create a file containing just the lines
  273.         (in-package "YOUR-PACKAGE")
  274.         (setq *hash-table* '#.*hash-table*)
  275. and compile it. The #. macro performs read-time evaluation of the
  276. expression following the dot, and so this compiles the data into the
  277. file. You may then load the file to restore the data. However, the
  278. resulting binary file is not portable between Lisp implementations,
  279. and sometimes not even for the same Lisp on different platforms. Also,
  280. some Lisps will treat the data as constant, and place it on pages in
  281. memory that are marked read-only (after it is loaded). If one tries to
  282. later modify the data, these Lisps will signal an error. Lucid CL only
  283. puts such constants in a read-only area when they appear inside
  284. functions, so this should be safe. Allegro CL doesn't seem to complain
  285. about modification if the data is a cons. DEC's VAXLisp, however, has
  286. problems with #. circular structures in .fas files. MCL seems to work
  287. well with using #. to save data (and even functions) to a file.
  288.  
  289. The other technique is to produce an ASCII representation of the Lisp
  290. objects which may then be saved to a file. To reproduce the data, one
  291. can load (or compile and load) the file. This technique is portable
  292. between different Lisps and platforms. Unfortunately, the resulting
  293. data is not necessarily EQ to the original. Kerry Koitzsch's
  294. save-object.lisp package is included in the Lisp Utilities Repository,
  295.    ftp.cs.cmu.edu:/user/ai/lang/lisp/code/ext/save_obj/
  296. The Lisp Utilities Repository is described in detail in the answer to
  297. question [6-1]. 
  298.  
  299. See also the discussion of MAKE-LOAD-FORM and MAKE-LOAD-FORM-SAVING-SLOTS 
  300. in CLtL2.
  301.  
  302. Here are some solutions to object persistence that use databases instead
  303. of file systems.
  304.  
  305. Free Persistent Object Storage systems include: 
  306.  
  307.    WOOD (William's Object Oriented Database) is a simple persistent
  308.    object store for MCL 2.0, written by Bill St. Clair
  309.    <bill@cambridge.apple.com>.  Its goal is to provide a way to
  310.    save/restore Lisp objects to/from disk.  It is available by anonymous
  311.    ftp from the MCL repository on cambridge.apple.com:/pub/MCL2/CONTRIB/.
  312.    Send bug reports to bug-wood@cambridge.apple.com. To be added to the
  313.    mailing list, send mail to info-wood-request@cambridge.apple.com.
  314.  
  315.    PCLOS is a persistent object store for CLOS that was implemented using
  316.    CLOS's metaobject protocol. It allowed multiple different storage
  317.    facilities to be used. The benefit of this approach is it lets you use
  318.    different storage facilities depending on your needs, ranging from a
  319.    full-blown database with concurrency control and recovery to a very
  320.    fast store that trades speed for functionality. For example, an
  321.    in-memory store that saves its state to disk periodically can be much
  322.    faster than traditional databases, but risks loss of data due to
  323.    crashes. Unfortunately, PCLOS was built on a very old version of CLOS,
  324.    so it is unusable in its current form, and there are no plans to
  325.    update it. The introductory MOP chapter in the book "Object-Oriented
  326.    Programming: The CLOS Perspective" (see [5-1] above) explains how to
  327.    do the rewrite in principle and shows how the CLOS MOP was used for
  328.    object persistence in PCLOS. See also 
  329.       1. Andreas Paepcke, "PCLOS: A Flexible Implementation of CLOS 
  330.          Persistence", in Proceedings of ECOOP-88, S. Gjessing and K.
  331.          Nygaard, editors, Lecture Notes in Computer Science, Springer
  332.          Verlag, pages 374-389, 1988.  [Explains the PCLOS architecture.]
  333.       2. Andreas Paepcke, "PCLOS: A Critical Review", in OOPSLA-89, 1989. 
  334.          [Uses PCLOS as a roadmap through the issues of object persistence.]
  335.       3. Andreas Paepcke, "PCLOS Reference Manual", Hewlett-Packard
  336.          Laboratories, December, 1991.
  337.    For more information about PCLOS, write to Andreas Paepcke
  338.    <paepcke@parc.xerox.com>. 
  339.  
  340.    GBB (see [6-3]) is a blackboard architecture with persistence of a
  341.    sort. Every object in GBB is held in RAM, and there are dump and
  342.    restore functions. It handles distributed object delivery and
  343.    function-call triggering of receiving processes.
  344.  
  345. Commercial Persistent Object Storage systems include: 
  346.  
  347.    AllegroStore is a high-performance object-oriented database management
  348.    system from Franz. It offers Allegro CL users persistent object
  349.    storage with very fast retrieval and update of object data.  It
  350.    provides query processing and transaction-based operation. Built on a
  351.    multi-client, multi-server architecture, it permits concurrent access
  352.    over a network to objects by multiple independent processes.  It uses
  353.    the ObjectStore ODBMS from Object Design Inc, and thus has both Lisp
  354.    and C interfaces and is also very fast.  The CLOS interface is based
  355.    on MOP, with dynamic class/schema modification and redefinition.
  356.    AllegroStore can handle large-scale applications with minimal impact
  357.    on performance. It uses page-faulting and page-locking mechanisms
  358.    instead of object locking, providing high throughput and low overhead
  359.    for concurrent access by multiple users.  Standard database features
  360.    include deadlock detection, referential integrity, and inverse
  361.    functions.  Exception handling is integrated into the Lisp condition
  362.    system. AllegroStore runs on Sparc, SGI, HP, RS/6000, and
  363.    MS-Windows/NT systems.  For more information, send email to
  364.    info@franz.com, write to Franz Inc., 1995 University Avenue, Berkeley,
  365.    CA 94704, call 1-800-333-7260, 510-548-3600, fax 510-548-8253, or
  366.    telex 340179 WUPUBTLXSFO.
  367.  
  368.    ITASCA ODBMS V2.2 is a distributed active object database management
  369.    system. ITASCA allows clients to transparently access data that is
  370.    distributed among multiple servers.  ITASCA supports full dynamic
  371.    schema modification that can be performed during any phase of the
  372.    software lifecycle.  Applications written in dissimilar and
  373.    incompatible languages, such as C/C++ and CLOS, can share objects through
  374.    ITASCA. ITASCA stores methods inside the database, promoting
  375.    reusability and maintainability.  ITASCA is based on work at MCC's
  376.    Object-Oriented and Distributed Systems Lab on the ORION system. For
  377.    more information, write to Itasca Systems, Inc., 7850 Metro Parkway,
  378.    Minneapolis, MN 55425, sales@itasca.com, 612-851-3155, fax 612-851-3157.
  379.    [Clint Hyde has written a MOP CLOS interface to Itasca, which has some
  380.    features not present in their interface. For a free copy of his source
  381.    code, send him mail to chyde@bbn.com.]
  382.  
  383.    Statice is a commercial product from Symbolics, that provides a
  384.    powerful persistent ODBMS. It runs on Symbolics Lisp Machines and soon
  385.    on Unix boxes under Lucid. 
  386.  
  387. ----------------------------------------------------------------
  388. Subject: [5-5] Given the name of a class, how can I get the names
  389.                of its slots?     
  390.  
  391. (defun class-slot-names (class-name)
  392.   "Given a CLASS-NAME, returns a list of the slots in the class."
  393.   (mapcar #'clos:slot-definition-name
  394.           (clos:class-slots (find-class class-name))))
  395.  
  396. (defmethod class-slot-names ((instance standard-object))
  397.   "Given an INSTANCE, returns a list of the slots in the instance's class."
  398.   (mapcar #'clos:slot-definition-name
  399.           (clos:class-slots (class-of instance))))
  400.  
  401. You can use CLASS-DIRECT-SLOTS instead of CLASS-SLOTS if you don't
  402. want inherited slots. Note that these functions are from the
  403. meta-object protocol specified in the original X3J13 draft spec
  404. (document X3J13/88-003), and may not be supported by all Lisps.
  405.  
  406. ----------------------------------------------------------------
  407. Subject: [5-6] Free CLOS software.
  408.  
  409. Software Repositories:
  410.  
  411.    The CLOS code repository is available by anonymous ftp to
  412.    nervous.cis.ohio-state.edu:/pub/lispusers/clos/ [128.146.61.200]
  413.    If you've got code you'd like to add to the repository, send
  414.    mail to Arun Welch, commonloops-request@cis.ohio-state.edu.
  415.    The CLOS code repository includes dag.lisp.Z and 3DGeometry.lisp.
  416.  
  417. CORBA:
  418.  
  419.    The CORBA (Common Object Request Broker Architecture) specification's
  420.    Dynamic Invocation Interfaces (DII) are a collection of interfaces for
  421.    writing extensible, distributed object applications.  NEC Systems
  422.    Laboratory Inc. has contributed both C and CLOS implementations of
  423.    these specification to the Object Management Group (OMG). The CORBA
  424.    specification (91-8-1) is available free to OMG members, and for $50
  425.    to non-members. To order the document, send mail to documents@omg.org,
  426.    or write to OMG, 492 Old Connecticut Path, Framingham, MA 01701, phone
  427.    508-820-4300, fax 508-820-4303. The DII implementation can be
  428.    retrieved via anonymous ftp from omg.org:/pub/ [192.67.184.64] as the
  429.    file NEC_DII/93-1-2.tar.Z. There are three dependencies in the
  430.    contributed DII implementations.  First, the CLOS images require an
  431.    Allegro CL license due to its use of the Lisp foreign function
  432.    interface.  Second, the C executables require Sun SparcStations, but
  433.    they can be re-compiled and re-linked for other architectures.  Third,
  434.    the implementation of the `Invoke' DII interface is considered
  435.    proprietary.  For further information, write to Don Vines, NEC Systems
  436.    Laboratory, Inc., C&C Software Technology Center (CSTC), 1901 Gateway
  437.    Drive, Irving, Texas 75038, call 214-518-3486, fax 214-518-3552, or
  438.    send email to dvines@syl.dl.nec.com.
  439.  
  440. ----------------------------------------------------------------
  441. Subject: [5-7] Common CLOS Blunders
  442.  
  443. This question is based on a document written by Marty Hall
  444. <hall@aplcenmp.apl.jhu.edu>. The full text of Marty's
  445. "Introduction to CLOS" handout is available by anonymous ftp from
  446.    ftp.cs.cmu.edu:/user/ai/lang/lisp/doc/intro/closintr.tgz
  447.  
  448. This question lists a variety of common errors that occur when writing
  449. CLOS code. It is extremely useful to glance through this list when
  450. debugging CLOS code.
  451.  
  452. [A] Omitting a set of parentheses around the arglist in DEFMETHOD.
  453.  
  454.     For example, writing 
  455.        (defmethod Area (Sq Square) ...)
  456.     instead of
  457.        (defmethod Area ((Sq Square)) ...)
  458.  
  459.     Lisp will accept the former, and think that you have two
  460.     unspecialized arguments instead of one argument specialized as a
  461.     Square. 
  462.  
  463. [B] Missing parentheses around the slot definition list in DEFCLASS.
  464.  
  465.     For example, writing
  466.        (defclass Rectangle (Polygon)
  467.      (Width ...)
  468.      (Height ...)) 
  469.     instead of
  470.        (defclass Rectangle (Polygon)
  471.      ((Width ...)
  472.       (Height ...)))
  473.  
  474.     Lisp will not accept the former, but the error message doesn't
  475.     always clearly identify the problem.
  476.  
  477. [C] Forgetting to include an empty slot definition list if you don't
  478.     define local slots in DEFCLASS.
  479.  
  480.     For example, writing 
  481.        (defclass Square (Rectangle)) 
  482.     instead of
  483.        (defclass Square (Rectangle) ())
  484.     Lisp will not accept the former.
  485.  
  486. [D] Referring to the class name instead of the instance variable in
  487.     DEFMETHOD. 
  488.  
  489.     For example, writing 
  490.        (defmethod Area ((Sq Square)) 
  491.      (* (Width Square) (Width Square))) 
  492.     instead of
  493.        (defmethod Area ((Sq Square)) 
  494.      (* (Width Sq) (Width Sq)))
  495.  
  496.     Lisp may give you a warning about an unknown free variable, but
  497.     probably won't even do that if you type the defmethod directly into
  498.     the Lisp Listener (Lucid doesn't). So you might not encounter a
  499.     problem until run-time.
  500.  
  501. [E] Forgetting that accessors are functions and thus could conflict
  502.     with built-in function names.
  503.  
  504.     For example, writing
  505.        (defclass Graphical-Object ()
  506.      ((Position :accessor Position)))
  507.     will signal an error, since you cannot redefine the built-in
  508.     POSITION function.  
  509.  
  510. [F] Putting the new value last instead of first in the definition of a 
  511.     SETF method. 
  512.  
  513.     For example, writing 
  514.        (defmethod (setf Area) ((Sq Square) (New-Area number))
  515.      (setf (Width Sq) (sqrt New-Area))) 
  516.     instead of
  517.        (defmethod (setf Area) ((New-Area number) (Sq Square))
  518.      (setf (Width Sq) (sqrt New-Area)))
  519.  
  520.    Lisp will accept the former, causing users to be later puzzled as
  521.    to why (setf (Area Square-1) 10) doesn't work.
  522.  
  523. [G] Putting the new value last instead of first in a call to a :writer
  524.     method.  
  525.  
  526.     For example, given
  527.        (defclass Circle () 
  528.      ((Radius :reader Radius :writer Set-Radius :initform 5)))
  529.        (setq Circle-1 (make-instance 'Circle))
  530.     and writing
  531.        (Set-Radius Circle-1 10)
  532.     instead of
  533.        (Set-Radius 10 Circle-1)
  534.  
  535. [H] Confusion about documentation strings in DEFMETHOD. 
  536.  
  537.     People often write code like
  538.        (defmethod Area ((Rect Rectangle))
  539.      "WIDTH times HEIGHT of the rectangle"
  540.      (* (Width Rect) (Height Rect)))
  541.     without clearly thinking about what this might mean.  Some people
  542.     think it will make a documentation string on the generic function that
  543.     can be retrieved by calling (DOCUMENTATION 'Area 'function) or the
  544.     equivalent emacs keystrokes. Others vaguely expect it to make a doc
  545.     string on each separate method, and that the call to DOCUMENTATION
  546.     will somehow be able to automagically figure out which method it
  547.     applies to.
  548.  
  549.     In fact, Lisp won't complain about this code, with the result that the
  550.     documentation is added to the method *object*, which beginners
  551.     probably know nothing about. 
  552.  
  553.     Use the :documentation entry in defgeneric to add a documentation
  554.     string to the generic function.
  555.  
  556. [I] Invalid :initargs are accepted by MAKE-INSTANCE.
  557.  
  558.     Many Lisp implementations will accept unknown keyword initargs without
  559.     complaint, even at the highest safety settings. 
  560.  
  561.     So the following code, which includes a typo of :SLOT1 instead of
  562.     :SLOT-1 in the call to make-instance
  563.        (defclass Foo ()
  564.     ((Slot-1 :accessor Slot-1 :initarg :Slot-1 :initform 5)))
  565.  
  566.        (setq Test (make-instance 'Foo :Slot1 10)) 
  567.     will not produce an error message, with the result that
  568.     (Slot-1 Test) returns 5, not 10.
  569.  
  570.     This is a bug in the implementation; all implementations are
  571.     supposed to flag this as an error. 
  572.  
  573. [J] Forgetting the class must exist before any method can specialize upon it. 
  574.  
  575.     Lisp programmers are used to being able to define functions in any
  576.     order, where even if FOO calls BAR, FOO can be defined first. But doing
  577.        (defmethod Area ((Rect Rectangle)) ...)
  578.        (defclass Rectangle (Polygon) ...)
  579.     is illegal. You have to define the class first.
  580.  
  581.     If while trying to debug the problem, you define the class by
  582.     evaluating the definition without reordering the code to put the
  583.     class first, you'll only run into problems later the next time you
  584.     try to recompile the code from scratch.
  585.  
  586.     Many experienced programmers put each class definition in its own
  587.     file at the top of the file, with methods for that class after it
  588.     in the file. Others opt to put all the class definitions for a
  589.     program in a single file that is loaded first, with methods in files
  590.     that are loaded later.
  591.  
  592. [K] Changing a method to apply to a more general class does not
  593.     supersede previous method. 
  594.  
  595.     For example, suppose a user writes
  596.        (defmethod Half-Area ((Rect Filled-Rectangle))
  597.      (/ (Area Rect) 2))
  598.     and then notices that this functionality could apply to all
  599.     Rectangles, not just Filled-Rectangles. They might then change the
  600.     class referenced in this method, under the specious intuition that by
  601.     changing the old defintion, they are replacing it. In fact, they are
  602.     actually adding a new, less-specific method.
  603.  
  604.     Now suppose that later on, they change this new method (in this
  605.     example, by adding a call to FLOAT to avoid returning a ratio),
  606.        (defmethod Half-Area ((Rect Rectangle))
  607.      (float (/ (Area Rect) 2)))
  608.     If they test it on an instance of Filled-Rectangle, they will be
  609.     puzzled as to why their new definition appears to have not taken
  610.     effect. But because the old definition specialized to Filled-Rectangle 
  611.     still exists, they're actually getting the old, more-specific definition.
  612.  
  613.     Moreover, the next time they restart a fresh Lisp and recompile
  614.     the code, the problem will magicly disappear, since the old
  615.     definition is no longer in the code. 
  616.  
  617. ----------------------------------------------------------------
  618. ;;; *EOF*
  619.  
  620.