Thoughts on creating objects in Lisp

If you work with classes in Lisp, you might want to hide the details of creating an object of a class. This practise is generally known as the factory method pattern. I’ll show a very simple example.

Let’s assume, you have defined the following class.

(defclass noun ()
    :accessor noun-spanish)
    :accessor noun-spanish-gender)
    :accessor noun-german)
    :accessor noun-german-gender)))

To create an object of this class, you have to call make-instance and setf the attributes (slots). To avoid writing this again and again, you can define the following function.

(defun create-noun (es es-gender de de-gender)
  (let ((n (make-instance 'noun)))
    (progn (setf (noun-spanish n) es)
       (setf (noun-spanish-gender n) es-gender)
       (setf (noun-german n) de)
       (setf (noun-german-gender n) de-gender)

You can then use this function to create objects of your class.

CL-USER> (defparameter *noun* (create-noun 'falda 'f 'Rock 'm))
CL-USER> (noun-german *noun*)
CL-USER> (noun-spanish *noun*)

While this is a very simple application of a factory method (or function), you might still find it useful.

Thoughts on creating objects in Lisp